Diff (diff 0.000 sec, rendering: 0.000 sec, diff len: 22 chars)
If you want to control your SBrick from Linux with Python code you need some way to make python talk "Bluetooth Low Energy" protocol. There are already some attempts to write some python libraries I had not sucess using any (NOTE: I am not a programmer). The one I found most promissory is Ian Harvey 'bluepy'.
But since python can execute commands from the operating system we can invoke gatttool almost like we do from command line:
gatttool -b 00:07:80:2E:2A:5D -i hci1 --char-write --handle=0x0025 --value=01000080
We just need 'call' from 'subprocess' library.
So to spin a motor on port A at 50% speed for just 2.5 seconds this is the most simple example:
#!/usr/bin/env python
from subprocess import call
def main():
call("gatttool --device=00:07:80:2E:2A:5D --adapter=hci1 --char-write --handle=0x0025 --value=01000080", shell=True)
if __name__ == "__main__":
main()
The following python script shows how to generate a sawtooth wave, starting with 80d (31%) and increase one step (0.4%) each 0.1 seconds until full speed (255d = 100%) and starting all over again until you press Control-C.
(I don't start at 0% because most LEGO motors don't react to lower values - my Power Functions M motors start spinning only at near 30%)
#!/usr/bin/env python
import sys, traceback, os
from subprocess import call
from time import sleep
RUN_A = "gatttool --device=00:07:80:2E:2A:5D --adapter=hci1 --char-write --handle=0x0025 --value=010000"
BREAK_A = "gatttool --device=00:07:80:2E:2A:5D --adapter=hci1 --char-write --handle=0x0025 --value=0000"
def main():
try:
# turn off motor
call(BREAK_A, shell=True)
sleep(0.1)
while(True):
for t in range(80,255):
print(t)
call(RUN_A+str(hex(t))[2:], shell=True)
sleep(0.1)
except (KeyboardInterrupt, SystemExit):
print("Exiting...")
except Exception:
traceback.print_exc(file=sys.stdout)
# turn off motor
call(BREAK_A, shell=True)
sys.exit(0)
if __name__ == "__main__":
main()
I use some ugly code like constants as a kind of macro commands and this piece of code
str(hex(t))[2:]
to convert from decimal to a string with the hexadecimal equivalent.