import serial, json, time
from serial.tools.list_ports import comports as list_serial_ports
def find_microbit():
"""
Finds the port to which the device is connected.
https://github.com/mu-editor/mu/blob/803153f661097260206ed2b7cc9a1e71b564d7c3/mu/contrib/microfs.py#L44
"""
ports = list_serial_ports()
for port in ports:
if "VID:PID=0D28:0204" in port[2].upper():
return port[0]
return None
port = find_microbit()
baudrate=115200
ser = serial.Serial(port, baudrate, timeout=1)
i = 0
while True:
data = {"a":i}
# data = "topic-sensor-data-x" + "\r\n"
data = json.dumps(data) + "\r\n"
# data = "a" + "\r\n"
data_bytes = data.encode("utf-8")
ser.write(data_bytes)
time.sleep(0.1)
read_data = ser.readline()
print("from microbit: {}".format(read_data))
i += 1
microbit
from microbit import *
def get_topic_and_data(b):
try:
b = b.strip()
json_str = str(b, 'utf-8')
json = eval(json_str)
display.show(str(json["a"])[-1])
return "a"
except:
display.show(str("!"))
while True:
r = uart.readline() # is bytes or none
if r:
d = get_topic_and_data(r)
if d:
# uart.write(b'ok' + b"\r\n")
uart.write(r)
卡顿的时候可能会把某个 \r 弄没掉 没有丢数据