Skip to content

Instantly share code, notes, and snippets.

@wwj718
Last active April 20, 2018 10:47
Show Gist options
  • Save wwj718/120e028370473dae534f434104cf6d72 to your computer and use it in GitHub Desktop.
Save wwj718/120e028370473dae534f434104cf6d72 to your computer and use it in GitHub Desktop.

pc上:

#!/usr/bin/env python
# encoding: utf-8

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:

# microbit
from microbit import *

def get_topic_and_data(b):
    try:
        json_str = str(b, 'utf-8')
        json = eval(json_str)
        display.show(str(json["a"])[-1])
    except:
        display.show(str("!"))


while True:
    r = uart.readline()  # is bytes or none
    if r:
        d = get_topic_and_data(r)
        uart.write(r) # urat.write(b"ok"+b"\r\n")
        
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment