Friday, September 10, 2010

When Python talk to Arduino

Yesterday I show a code where when we send a 't' via serial connection, the LED will blink while the arduino board, send back a series of string via serial, the code below is what I used to run on arduino, to test with the python code.
link
int incomingByte = 0;
int ledPin = 13;
void setup(){
Serial.begin(9600);
pinMode(ledPin,OUTPUT);
}
void loop(){
if(Serial.available() > 0){
incomingByte = Serial.read();
if(incomingByte == 116){
Serial.println("Blinky");
digitalWrite(ledPin,HIGH);
delay(1000);
digitalWrite(ledPin,LOW);
}
}
}
view raw gistfile1.c hosted with ❤ by GitHub


In the arduino development environment, there is a serial monitor that do the the testing.


Since it is just a standard serial interface, so one can just do it anyway they want. Here I show how to do it via python. First what we need, is the pyserial library, you can install it using pip or easy_install or grab it from pyserial site

To install, just use to following command. if you need more detail, read the docs, because I use python 2.7 it just works for me,
pip pyserial
or
easy_install pyserial
To use it, with the arduino code from the top of the page just, do the following
link
import serial
s = serial.Serial(2)
s.write('t')
print(s.readline())
view raw gistfile1.py hosted with ❤ by GitHub


The line s=serial.Serial(2) points to com3 on windows, on linux it should be s=serial.Serial('/dev/ttyUSB0'), or other port that shown by the arduino serial monitor. Pyserial actually have a few options on the Serial object, but I found that for arduino, the default is adequate.

And this is how to use arduino to interface to your computer using python. enjiy

No comments:

Post a Comment