Skip to content

Instantly share code, notes, and snippets.

@max6cn
Created September 29, 2016 22:14
Show Gist options
  • Save max6cn/b9de988a4c20f6181de50037862abe21 to your computer and use it in GitHub Desktop.
Save max6cn/b9de988a4c20f6181de50037862abe21 to your computer and use it in GitHub Desktop.
Test Scripts for Sensor Project
import serial, time
import sys
import threading
# initialization and open the port
# possible timeout values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float allowed, timeout block call
ser = serial.Serial()
# ser.port = "/dev/ttyUSB0"
ser.port = "COM3"
# ser.port = "/dev/ttyS2"
ser.baudrate = 115200
ser.bytesize = serial.EIGHTBITS # number of bits per bytes
ser.parity = serial.PARITY_NONE # set parity check: no parity
ser.stopbits = serial.STOPBITS_ONE # number of stop bits
# ser.timeout = None #block read
ser.timeout = 1 # non-block read
# ser.timeout = 2 #timeout block read
ser.xonxoff = False # disable software flow control
ser.rtscts = False # disable hardware (RTS/CTS) flow control
ser.dsrdtr = False # disable hardware (DSR/DTR) flow control
ser.writeTimeout = 2 # timeout for write
def monitor():
# flush input buffer, discarding all its contents
ser.flushInput()
time.sleep(0.5)
numOfLines = 0
while True:
# response =
sys.stdout.write(ser.readline())
numOfLines = numOfLines + 1
if numOfLines >= 500:
break
ser.close()
def sendcmd():
# flush output buffer, aborting current output
# write data
ser.flushOutput()
while True:
s = "S60 {\"ID\":\"ABCD-EFGH-HIJK-LHMO\",\"S\":23,\"P1\":102.38,\"P2\":100.68} "
ser.write(s)
sys.stdout.write(s + "\n")
time.sleep(10)
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
if ser.isOpen():
try:
r = threading.Thread(target=monitor)
w = threading.Thread(target=sendcmd)
r.start()
w.start()
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment