Pyserial problem with Arduino - works with the Python shell but not in a program
The program should make a LED on the board blink when it read data from the USB.
The way I do it is:
#!/usr/bin/env python import serial ser = serial.Serial("/dev/ttyACM0", 9600) ser.write("something")
This doesn't work, but doing each step in the interactive shell works:
>>> import serial >>> ser = serial.Serial("/dev/ttyACM0", 9600) >>> ser.write("something")
I've tried using a timeout in the script before closing, but that didn't help. What am I doing wrong?
When you open the serial port, this causes the Arduino to reset. Since the Arduino takes some time to bootup, all the input goes to the bitbucket (or probably to the bootloader which does god knows what with it). If you insert a sleep, you wait for the Arduino to come up so your serial code. This is why it works interactively; you were waiting the 1.5 seconds needed for the software to come up.
I confirmed that opening the serial port resets my Arduino Uno; I flashed a program which will blink the LED from the
setup() routine -- calling
open("/dev/ttyACM0") was sufficient to trigger the reset. This is IMHO a confusing and undocumented wrinkle in the serial support.