It’s been a while since I last played with an arduino . I think it was while making some demos for bike lazer tag (more of that to come)… There seem to be a few examples online of how to get your arduino playing with python, but most of then seem to focus on getting servos to move around – which is cool, but surely the fun to be had with an arduino is getting it to talk ‘to’ your computer.
So… with this in mind, and my little box of components that I brought with me from London, we will see what we can get going. I’m not going to put everything up here, but if you are interested in anything just drop me an email ben(at)beoliver(dot com).
Firstly, I would recommend downloading pyserial. It works with both 2.X and 3.X python. ( i will be using 2.X for the moment ).
Secondly, you are obviously going to need an arduino for this !
LETS BEGIN…
1. upload an Arduino sketch with the following :
void setup() {
Serial.begin(9600);
}
void loop() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
}
All we are doing here is telling the Arduino to start a serial connection, and any value that is recorded on Analog pin 0 should be sent via the Serial connection.
2. after installing pyserial we will begin by writing the following:
#!/bin/env python import serial import time # plug in your arduino and look in /dev name = '/dev/tty.usbserial-A9007W1P' baud = 9600 arduino = serial.Serial(name, baud) time.sleep(2) # pause as the Arduino is restarted by the serial connection while True: output = arduino.readline() print output
And there you go! you are reading the output from your arduino (this is just the same as the serial monitor in the Arduino app).
Now the first thing you might notice is that the output is read as a string. and secondly you sometimes get non numerical characters :
’1023′
’100?30′
’1023′
we will write a tiny function that will test the output and return an int if possible:
def str2int(input):
try:
return int(input)
except ValueError:
pass
# our output can now be:
output = str2int( arduino.readline() )
This now means that our output can be evaluated as an integer.










