Last active
April 20, 2018 07:25
-
-
Save wwj718/603c443c8f52042eecbeeabc8c430c35 to your computer and use it in GitHub Desktop.
microbit serial input/output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
pc 控制microbit | |
双工通道 编程风格类似socket | |
''' | |
## pc | |
import serial | |
ser = serial.Serial('/dev/tty.usbmodem1412', 9600, timeout=5) | |
data = "abc".encode("utf-8") | |
# data = bytes('abc\n',"UTF-8") | |
ser.write(data) | |
## microbit | |
from microbit import * | |
uart.init(9600) | |
while True: | |
_data = uart.readline() | |
if _data: | |
data = str(_data,'utf-8') # bytes,_data.decode("utf-8")不可用 | |
display.scroll(data) | |
# print(data) | |
sleep(20) | |
############ | |
''' | |
pc中读取microbit输出 | |
''' | |
## microbit | |
import microbit | |
while True: | |
microbit.sleep(1) | |
print("hello") | |
## pc | |
import serial | |
ser = serial.Serial('/dev/tty.usbmodem1412', 115200, timeout=5) | |
data = ser.readline() | |
print(data) | |
line = str(data,'utf-8').strip() | |
# data.decode("utf-8") | |
''' | |
问题: 如何输出数值组? | |
序列化还原 | |
>>> a = [34, 58, 62] | |
>>> b = ",".join([str(i) for i in a]) # 将数字列表转化为字符串列表,这样利于传输 | |
>>> [int(i) for i in b.split(",")] #将字符串列表还原为数字 | |
[34, 58, 62] | |
''' |
microbit:
try:
# json_str = str(b, 'utf-8')
json = eval(b)
# print(type(json))
# print(json)
display.scroll(str(json["topic"]), wait=True, loop=False)
except:
display.scroll(b"!")
外部
data = '{"topic": "sensor", "data": ""}'
data_bytes = data.encode("utf-8")
self.ser.write(data_bytes)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
或者使用json
eval都行,eval注意注意安全问题