Skip to content

Instantly share code, notes, and snippets.

@xychix
Created September 20, 2015 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xychix/66039e398af8eae2835a to your computer and use it in GitHub Desktop.
Save xychix/66039e398af8eae2835a to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
# Read the output of an Arduino which may be printing sensor output,
# and at the same time, monitor the user's input and send it to the Arduino.
# See also
# http://www.arcfn.com/2009/06/arduino-sheevaplug-cool-hardware.html
import sys, serial, select
from time import sleep
class Arduino() :
def run(self, baud=9600) :
# Port may vary, so look for it:
baseports = ['/dev/ttyUSB', '/dev/ttyACM']
self.ser = None
self.points = []
for baseport in baseports :
if self.ser : break
for i in xrange(0, 8) :
try :
port = baseport + str(i)
self.ser = serial.Serial(port, baud, timeout=1)
print "Opened", port
break
except :
self.ser = None
pass
if not self.ser :
print "Couldn't open a serial port"
sys.exit(1)
self.ser.setDTR(False)
sleep(1)
self.ser.flushInput()
self.ser.setDTR(True)
while True :
# Check whether the user has typed anything:
inp, outp, err = select.select([sys.stdin, self.ser], [], [], .2)
# Check for user input:
if sys.stdin in inp :
line = sys.stdin.readline().strip()
if line == "wipe":
print "Clearing data"
self.points=[]
self.ser.write(line)
# check for Arduino output:
if self.ser in inp :
line = self.ser.readline().strip()
print "Arduino:", line
if line.count(',') == 4:
# must be a line with values
self.points.append((float(line.split(',')[0])/1000000,float(line.split(',')[2])/1000))
if line == "End":
import matplotlib.pyplot as plt
plt.xlabel('FREQ')
plt.ylabel('VSWR')
plt.plot(*zip(*self.points))
plt.show()
arduino = Arduino()
try :
if len(sys.argv) > 1 :
print "Using", sys.argv[1], "baud"
arduino.run(baud=sys.argv[1])
else :
arduino.run()
except serial.SerialException :
print "Disconnected (Serial exception)"
except IOError :
print "Disconnected (I/O Error)"
except KeyboardInterrupt :
print "Interrupt"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment