Skip to content

Instantly share code, notes, and snippets.

@mafrosis
Created May 17, 2013 21:41
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 mafrosis/5602187 to your computer and use it in GitHub Desktop.
Save mafrosis/5602187 to your computer and use it in GitHub Desktop.
Arduino serial port monitor
#! /usr/bin/env python
import serial
import time
PORT = "/dev/tty.usbmodemfd1121"
RECONNECT_SLEEP = 5
MONITOR_SLEEP = 0.2
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
states = enum("CONNECTING", "RUNNING")
class SerialMonitor():
ser = None
state = None
def __init__(self, port):
self.port = port
self.state = states.CONNECTING
def connect(self):
try:
self.ser = serial.Serial(self.port, 9600, timeout=0)
self.ser.setRTS(True)
self.ser.setDTR(True)
except serial.serialutil.SerialException:
return False
return True
def monitor(self):
try:
data = self.ser.readline()
if len(data) > 0:
print data.strip()
except OSError:
print "Disconnected"
self.state = states.CONNECTING
time.sleep(1)
def run(self):
self.alive = True
try:
while self.alive:
if self.state == states.CONNECTING:
if self.connect():
print "Connected"
self.state = states.RUNNING
else:
print "Failed to connect"
time.sleep(RECONNECT_SLEEP)
elif self.state == states.RUNNING:
self.monitor()
time.sleep(MONITOR_SLEEP)
except KeyboardInterrupt:
self.alive = False
finally:
if self.ser is not None:
self.ser.close()
if __name__ == "__main__":
sr = SerialMonitor(PORT)
sr.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment