I want to use Python to send commands to an EV3 brick. In C++ things work as expected - for instance, this starts the motor on port A and then stops it after a while:
#include <unistd.h>
#include <fcntl.h>
int main()
{
// command to start motor on port A at speed 20
char start_motor[] = "\x0C\x00\x00\x00\x80\x00\x00\xA4\x00\x01\x14\xA6\x00\x01";
// command to stop motor on port A
char stop_motor[] = "\x09\x00\x01\x00\x80\x00\x00\xA3\x00\x01\x00";
// send commands to EV3 via bluetooth
int bt = open("/dev/tty.EV3-SerialPort", O_RDWR);
write(bt, start_motor, 14);
usleep(500000);
write(bt, stop_motor, 11);
close(bt);
}
When I try the same thing in Python, however, only the first command is executed (the motor starts but it doesn't stop):
import time
# command to start motor on port A at speed 20
start_motor = '\x0C\x00\x00\x00\x80\x00\x00\xA4\x00\x01\x14\xA6\x00\x01' + '\n'
# command to stop motor on port A
stop_motor = '\x09\x00\x01\x00\x80\x00\x00\xA3\x00\x01\x00' + '\n'
# send commands to EV3 via bluetooth
with open('dev/tty.EV3-SerialPort', mode = 'w') as bt:
bt.write(start_motor)
time.sleep(5)
bt.write(stop_motor)
I have also tried: suppressing the \n
; using os.open('dev/tty.EV3-SerialPort', os.O_RDWR)
; using bt.flush()
; using os.fsync(bt)
; using bt = open(... (instead of with)
; and changing the mode and buffering arguments of the open method. Nothing worked.
Well, it does work if I close the tty and open it again, but this sounds inefficient:
# ...
with open('dev/tty.EV3-SerialPort', mode = 'w') as bt:
bt.write(start_motor)
time.sleep(5)
with open('dev/tty.EV3-SerialPort', mode = 'w') as bt:
bt.write(stop_motor)
So, what am I missing here?
(OS X 10.9.3, Python 2.7.6, EV3 [31313])