python串⼝连续数据_Python代码从串⼝连续接收可变数据通常,您与微通信所做的⼯作是将单个字符⽤于轻量级或创建通信协议。基本上你有⼀个开始标志,结束标志和某种校验和,以确保数据正确传输。有很多⽅法可以做到这⼀点。
以下代码适⽤于Python 3.您可能必须对字节数据进⾏更改。
# On micro
data = b"[Hello,1234]"
serial.write(data)
在电脑上,你会运⾏,如果您使⽤的是GUI
def read_data(ser, buf=b'', callback=None):
if callback is None:
callback = print
# Read enough data for a message
buf += ad(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 += ad(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显⽰数据时,您可以让线程在后台读取数据。
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()
python怎么读取串口数据# 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
注意,在线程例⼦中,我使⽤回调它是被作为⼀个变量传递后来被称为函数。另⼀种⽅式是将数据放⼊队列中,然后在队列的另⼀部分处理队列中的数据。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。