Reading PIXAXE URF ERF output with Python
August 24, 2013
Previously, we've talked about reading light level data via an LDR and a PICAXE and transmitting this wirelessly using an ERF and URF pair. (http://drumcoder.co.uk/blog/2013/aug/24/ldr-wireless-sensor/).
In that article, I'm reading the output using a simple cat
command, but I'd like to take more control and read it with python.
Libraries
First, install pyserial:
$ sudo easy_install pyserial
Once we have this, we can import the serial library into our python code.
Python
The following simple program will read the output, look for the underscore terminator, and output one line for each reading from the LDR:
import serial lSerialPort = serial.Serial('/dev/ttyACM0',9600,timeout=2) lBuffer = '' while True: lChar = lSerialPort.read() if lChar == '_': print lBuffer lBuffer = '' elif lChar > 0: lBuffer += lChar
Here's sample output:
LIGHT00924 LIGHT00914 LIGHT00816 LIGHT00318 LIGHT00282 LIGHT00271 LIGHT00264 LIGHT00260
Improvements
To improve the parsing, we're going to change the PICAXE program so that it outputs LIGHT, then a colon, then the value, then an underscore. We can then use the colon to easily split the sensor name from the value. Here's the PICAXE program:
main: setfreq m8 high C.1 readadc10 C.2, w1 bintoascii w1,b4,b5,b6,b7,b8 serout C.4,N9600_8,("LIGHT:",b4,b5,b6,b7,b8,"_") pause 1000 low C.1 pause 1000 goto main
Here's the python program used to read it:
import serial lSerialPort = serial.Serial('/dev/ttyACM0',9600,timeout=2) lBuffer = '' while True: lChar = lSerialPort.read() if lChar == '_': lSensor, lValue = lBuffer.split(':') print "%s=%s" % (lSensor, lValue) lBuffer = '' elif lChar > 0: lBuffer += lChar
and the output (I managed to get the sensor all the way down to 170ish by covering the LDR completely with my hand):
LIGHT=00926 LIGHT=00926 LIGHT=00925 LIGHT=00414 LIGHT=00222 LIGHT=00196 LIGHT=00187 LIGHT=00182 LIGHT=00179 LIGHT=00177 LIGHT=00175 LIGHT=00171 LIGHT=00171 LIGHT=00921 LIGHT=00922 LIGHT=00921