GrabData.py

#!/usr/bin/env python

'''
grabdata.py
Eric Ayars
7/31/11

Thrown-together program to collect data from an arduino, Workshop W20,
Summer '11 AAPT meeting, Omaha Nebraska.

This program is matched to the Arduino program 'senddata.pde'.

Program should be called with two parameters: the number of points to 
collect (at a rate of 10/s) and the filename where the data should be saved.
Plotting the data is done by default, but can be commented out in the last
two lines.

'''

import serial, sys, time
import pylab as pl

port = '/dev/tty.usbmodem621'
N = int(sys.argv[1])
if N>255:
    print '255 points max: 255 requested from Arduino.'
    N=255
if N<0:
    N=0

filename = sys.argv[2]

# start the serial port
ser = serial.Serial(port, 57600, timeout=2)
# The following line is necessary to give the arduino time to start
# accepting stuff.
time.sleep(2)
#time.sleep(1.5)

times = pl.zeros([N])
measurements = pl.zeros([N])

# Tell the Arduino how many points to grab
# the number will be sent as a char, thus the limit of 255.
ser.write(chr(N))

# Now grab that many
for i in range(N):
    # read a line from the serial port
    line = ser.readline()

    # testing
    print line

    # split the line into milliseconds and value
    brokenline = line.split()
    times[i] = int(brokenline[0])
    measurements[i] = int(brokenline[1])

# change times to seconds (currently in millis())
times = pl.array([(times[i]-times[0])/1000.0 for i in range(N)])

# Save the data
file = open(filename, 'w')
for j in range(N):
    file.write('%f\t%d\n' % (times[j], measurements[j]) )
file.close()

# plot data
pl.plot(times, measurements, 'ro-')
pl.xlabel('Time (s)')
pl.ylabel('Raw A/D value (10-bit)')
pl.show()

Generated by GNU enscript 1.6.4.