Skip to content

Instantly share code, notes, and snippets.

@wwj718
Created April 20, 2018 11:13
Show Gist options
  • Save wwj718/309b5500d999eeba894ea3bf071c04a9 to your computer and use it in GitHub Desktop.
Save wwj718/309b5500d999eeba894ea3bf071c04a9 to your computer and use it in GitHub Desktop.
为何外部写入的和读出的不一致
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)
@wwj718
Copy link
Author

wwj718 commented Apr 20, 2018

卡顿的时候可能会把某个 \r 弄没掉 没有丢数据

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment