Created
April 17, 2021 13:42
-
-
Save thgie/af25d4ee34cc311e9b9c615d50a102d4 to your computer and use it in GitHub Desktop.
Read serial output from micro:bit in a phyton program. Via https://stackoverflow.com/questions/58043143/how-to-set-up-serial-communication-with-microbit-using-pyserial
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
from microbit import * | |
while True: | |
x = accelerometer.get_x() | |
y = accelerometer.get_y() | |
z = accelerometer.get_z() | |
print("x, y, z:", x, y, z) | |
sleep(500) |
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
# pip3 install pyserial --user | |
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment