Arduino+Python=PySerial

LogoOver the last few months I have learned how to program with Python. With one of the upcoming projects that I am working on it would be nice to have a computer’s display to view the data collected by a rover in real-time as well as crunch numbers while the rover completes its  mission. The rover will have an Arduino as a brain. What I found after some searching was pySerial. This is a really neat piece of software that allows Python to send and receive data much like the Serial Monitor does.

pySerial is available to download at

Once you download it open up Terminal and type in:

tar xfvz /Users/*Account*/Downloads/pyserial-2.6.tar.gz
cd pyserial-2.6
sudo python setup.py install

Open up Idle and type in:

import serial

Assuming that no error messages pop up everything is good to go.

Now to test it out, upload the below sketch to your Arduino. I do not know how this will or will not work on Arduino clones.

void setup() {
 Serial.begin(9600);
 Serial.println("Ready");
}

void loop() {
 char inByte = ' ';
 if(Serial.available()){
 char inByte = Serial.read();
 Serial.println(inByte);
 }
 delay(100);
}

Next in Idle create a new window and create the below program.

from time import sleep
import serial
ser = serial.Serial('/dev/tty.usbmodem1d11', 9600)
counter = 32 # Below 32 everything is gibberish
while True:
 counter +=1
 ser.write(str(chr(counter))) # Convert the decimal number to ASCII
 print ser.readline() # Read the output from the Arduino
 sleep(.1) # Delay for one tenth of a second
 if counter == 255:
 counter = 32

Two things to keep in mind. To determine what serial port your Arduino is connected to look at the bottom right corner of your Arduino sketch. Whatever that is should be what is in quotes in line 3 of the Python program.

F8YBEW7HAWSI81Q.LARGE

You can also change the baud rate in line 3 of the Python program and line 2 of the Arduino program as long as they stay the same.

Once you run the program it will print out the majority of ASCII characters. By first sending them to the Arduino, which will in turn send it back to the computer that Python then prints out.

Screen Shot 2012-12-29 at 5.42.41 PM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s