通常,您与微通信所做的是将单个字符用于轻量级的东西或创建通信协议。基本上,您有一个开始标志、结束标志和某种校验和,以确保数据正确传递。有很多方法可以做到这一点。
以下代码适用于 Python 3。您可能需要对字节数据进行更改。
# On micro
data = b"[Hello,1234]"
serial.write(data)
在您将运行的计算机上
def read_data(ser, buf=b'', callback=None):
if callback is None:
callback = print
# Read enough data for a message
buf += ser.read(ser.inwaiting()) # If you are using threading +10 or something so the thread has to wait for more data, this makes the thread sleep and allows the main thread to run.
while b"[" not in buf or b"]" not in buf:
buf += ser.read(ser.inwaiting())
# There may be multiple messages received
while b"[" in buf and b']' in buf:
# Find the message
start = buf.find(b'[')
buf = buf[start+1:]
end = buf.find(b']')
msg_parts = buf[:end].split(",") # buf now has b"Hello, 1234"
buf = buf[end+1:]
# Check the checksum to make sure the data is valid
if msg_parts[-1] == b"1234": # There are many different ways to make a good checksum
callback(msg_parts[:-1])
return buf
running = True
ser = serial.serial("COM10", 9600)
buf = b''
while running:
buf = read_data(ser, buf)
如果您使用的是 GUI,线程化很有用。然后你可以让你的线程在后台读取数据,而你的 GUI 显示数据。
import time
import threading
running = threading.Event()
running.set()
def thread_read(ser, callback=None):
buf = b''
while running.is_set():
buf = read_data(ser, buf, callback)
def msg_parsed(msg_parts):
# Do something with the parsed data
print(msg_parsed)
ser = serial.serial("COM10", 9600)
th = threading.Thread(target=thread_read, args=(ser, msg_parsed))
th.start()
# Do other stuff while the thread is running in the background
start = time.clock()
duration = 5 # Run for 5 seconds
while running.is_set():
time.sleep(1) # Do other processing instead of sleep
if time.clock() - start > duration
running.clear()
th.join() # Wait for the thread to finish up and exit
ser.close() # Close the serial port
请注意,在线程示例中,我使用了一个回调,它是一个作为变量传递并稍后调用的函数。另一种方法是将数据放入队列中,然后在代码的不同部分处理队列中的数据。