Take the 2-minute tour ×
LEGO® Answers is a question and answer site for LEGO® and building block enthusiasts. It's 100% free, no registration required.

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])

share|improve this question

1 Answer 1

up vote 2 down vote accepted

Works for me if you set buffering to 0 and get rid of the newlines.

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'

# command to stop motor on port A
stop_motor = '\x09\x00\x01\x00\x80\x00\x00\xA3\x00\x01\x00'

# send commands to EV3 via bluetooth
with open('/dev/tty.EV3-SerialPort', 'w', 0) as bt:
    bt.write(start_motor)
    time.sleep(5)
    bt.write(stop_motor)
share|improve this answer
    
It worked! I could swear I had tried buffering=0, but clearly I was wrong. –  Thiago Marzagão Jun 21 at 21:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.