Skip to content

Instantly share code, notes, and snippets.

@jezdean
Last active January 1, 2017 22:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jezdean/be25f0730a932c0a1b80683dd3a25b40 to your computer and use it in GitHub Desktop.
Save jezdean/be25f0730a932c0a1b80683dd3a25b40 to your computer and use it in GitHub Desktop.
Python program to communicate with a microbit
from guizero import *
import serial
from serial.serialutil import SerialException
from serial.tools import list_ports
def connect():
try:
ser.open()
ser.write("from microbit import * \r".encode())
except SerialException:
alerts.error(app, "No Connection! Unplug microbit and try again")
def disconnect():
ser.close()
""" send_data() function
run when send_button is clicked. Gets data from faces_to_send_list
and writes to serial port as bytes
1. .get selected face from faces_to_send_list
2. convert to bytes
3. .write to serial port
Alternatively, 1 + 2 + 3 all on the same line:
ser.write((faces_to_send_list.get() + '\r').encode())
"""
def send_data():
command_to_send = faces_to_send_list.get() + '\r'
command_to_send_bytes = command_to_send.encode()
try:
ser.write(command_to_send_bytes)
except SerialException:
alerts.error(app, "Could not Send. Connected?")
""" find_microbit_comport() function
returns COM port / device the microbit is attached to.
For each com port on the computer, check whether the
attached device's product ID and vendor ID match
the microbit's.
"""
def find_microbit_comport():
ports = list(list_ports.comports())
for p in ports:
if (p.pid == 516) and (p.vid == 3368):
return str(p.device)
""" Main Program """
ser = serial.Serial()
ser.baudrate = 115200
ser.port = find_microbit_comport()
# Window setup
app = App(layout='grid',
height='300',
width='200',
title="Python Microbit Smile")
# button_box and its elements
button_box = Box(app, grid=[0, 0])
connect_button = PushButton(button_box,
text="Connect",
command=connect,
padx=3,
pady=3)
disconnect_button = PushButton(button_box,
text="Disconnect",
command=disconnect,
padx=3,
pady=3)
# faces box and its elements
face_box = Box(app, grid=[0, 1])
faces_to_send_list = ButtonGroup(face_box, [
["Happy", "display.show(Image.HAPPY)"],
["Sad", "display.show(Image.SAD)"],
["Silly", "display.show(Image.SILLY)"],
["Yes", "display.show(Image.YES)"],
["No", "display.show(Image.NO)"],
["Pacman", "display.show(Image.PACMAN)"],
["Cow", "display.show(Image.COW)"]
],
"display.show(Image.HAPPY)"
)
send_button = PushButton(face_box,
text="Send",
command=send_data)
# render app window
app.display()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment