以下 python 3 代码使用 microbit 的 VID 和 PID 扫描串行端口,直到找到连接到 microbit 的端口。然后脚本将显示端口信息。在此之后,脚本会显示从 microbit 通过串行端口发送的任何内容。
您可以使用端口名称来设置 Tera Term,或者让脚本继续显示来自串行端口的数据。microbit 的默认波特率为 115200。在下面的示例输出中,端口名称为 COM5。每次拔下并重新插入 microbit 时,端口名称都会更改。
示例输出:
starting
looking for microbit
scanning ports
port: COM5 - mbed Serial Port (COM5)
pid: 516 vid: 3368
found target device pid: 516 vid: 3368 port: COM5
opening and monitoring microbit port
代码:
import serial
import serial.tools.list_ports as list_ports
PID_MICROBIT = 516
VID_MICROBIT = 3368
TIMEOUT = 0.1
def find_comport(pid, vid, baud):
''' return a serial port '''
ser_port = serial.Serial(timeout=TIMEOUT)
ser_port.baudrate = baud
ports = list(list_ports.comports())
print('scanning ports')
for p in ports:
print('port: {}'.format(p))
try:
print('pid: {} vid: {}'.format(p.pid, p.vid))
except AttributeError:
continue
if (p.pid == pid) and (p.vid == vid):
print('found target device pid: {} vid: {} port: {}'.format(
p.pid, p.vid, p.device))
ser_port.port = str(p.device)
return ser_port
return None
def main():
print('looking for microbit')
ser_micro = find_comport(PID_MICROBIT, VID_MICROBIT, 115200)
if not ser_micro:
print('microbit not found')
return
print('opening and monitoring microbit port')
ser_micro.open()
while True:
line = ser_micro.readline().decode('utf-8')
if line: # If it isn't a blank line
print(line)
ser_micro.close()
if __name__ == '__main__':
print('starting')
main()
print('exiting')