79 lines
1.7 KiB
Python
79 lines
1.7 KiB
Python
"""
|
|
Listen to serial, return most recent numeric values
|
|
Lots of help from here:
|
|
http://stackoverflow.com/questions/1093598/pyserial-how-to-read-last-line-sent-from-serial-device
|
|
"""
|
|
from threading import Thread
|
|
import time
|
|
import serial
|
|
import struct
|
|
|
|
last_received = ''
|
|
profile = []
|
|
|
|
PI_TS_MIN = 0
|
|
PI_TS_MAX = 1
|
|
PI_TL = 2
|
|
PI_TP = 3
|
|
PI_TIME_MAX = 4
|
|
|
|
PI_RAMP_UP_MIN = 5
|
|
PI_RAMP_UP_MAX = 6
|
|
PI_RAMP_DOWN_MIN = 7
|
|
PI_RAMP_DOWN_MAX = 8
|
|
|
|
PI_TS_DURATION_MIN = 9
|
|
PI_TS_DURATION_MAX = 10
|
|
PI_TL_DURATION_MIN = 11
|
|
PI_TL_DURATION_MAX = 12
|
|
PI_TP_DURATION_MIN = 13
|
|
PI_TP_DURATION_MAX = 14
|
|
|
|
def receiving(ser):
|
|
global last_received
|
|
buffer = ''
|
|
ser.write(chr(255))
|
|
ser.flush()
|
|
profile = struct.unpack("hhhhhhhhhhhhhhh", ser.read(30))
|
|
ser.flushInput()
|
|
while 1:
|
|
ser.write(chr(254))
|
|
ser.flush()
|
|
last_received = ser.read(11)
|
|
print repr(last_received)
|
|
ser.flushInput()
|
|
|
|
|
|
class SerialData(object):
|
|
def __init__(self, init=50):
|
|
try:
|
|
self.ser = ser = serial.Serial(
|
|
port='/dev/ttyUSB0',
|
|
baudrate=9600, timeout=2)
|
|
except serial.serialutil.SerialException:
|
|
#no serial connection
|
|
self.ser = None
|
|
else:
|
|
Thread(target=receiving, args=(self.ser,)).start()
|
|
|
|
def next(self):
|
|
if not self.ser:
|
|
return 100 #return anything so we can test when Arduino isn't connected
|
|
|
|
try:
|
|
return int(struct.unpack("hhhhhb", last_received)[1])
|
|
except Exception, e:
|
|
print e
|
|
return 0
|
|
|
|
|
|
def __del__(self):
|
|
if self.ser:
|
|
self.ser.close()
|
|
|
|
if __name__=='__main__':
|
|
s = SerialData()
|
|
for i in range(500):
|
|
time.sleep(1)
|
|
print s.next()
|