Arduino serial communication and Python


Question

Possible Duplicate:
Pyserial problem with Arduino - works with the Python shell but not in a program

So I just got myself an Arduino Uno, and now I'm trying to communicate with it using USB. I've got it working with the Serial Monitor provided by the Arduino IDE, and now I'm testing it with Python.

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?

1
0
5/23/2017 11:59:40 AM

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.

8
2/11/2011 11:33:15 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon