Enter MicroPython

Enter MicroPython

Introduction to MicroPython, specifically for ESP8266 (Wemos D1 Mini Pro) and BBC Micro:bit

Transcript

  1. 2.

    What is MicroPython MicroPython is a lean and efficient implementation

    of the Python 3 programming language that includes a small subset of the Python standard library and is optimised to run on microcontrollers and in constrained environments Just 256k of code space and 16k of RAM!
  2. 3.

    Features of Micropython • Python compiler + runtime that runs

    on bare-metal • REPL + ability to run and import scripts from the filesystem • Arbitrary precision integers, closures, list comprehension, generators, exception handling...
  3. 5.
  4. 6.

    The ESP8266 The ESP8266 is a low-cost Wi-Fi chip with

    full TCP/IP stack and MCU (Micro Controller Unit) capability produced by Espressif Systems Microcontroller ESP-8266EX Operating Voltage 3.3V Digital I/O Pins 11 Analog Input Pins 1(Max input: 3.2V) Clock Speed 80MHz/160MHz Flash 16M bytes Length 34.2mm Width 25.6mm Weight 2.5g
  5. 7.

    MicroPython installation • Download a firmware for the ESP8266 (http://micropython.org/download#esp8266)

    • Install esptool.py ◦ pip install esptool • Connect the board and take note of the port (e.g. /dev/ttyUSB0) that shows up in the output of dmesg command • Erase the flash memory of the board: ◦ esptool.py --port /dev/ttyUSB0 erase_flash • Flash with the firmware: ◦ esptool.py --port /dev/ttyUSB0 write_flash -fm dio -fs 32m 0 esp8266-20170108-v1.8.7.bin
  6. 8.

    Using the REPL Install picocom and connect to the serial

    interface: picocom -b 115200 /dev/ttyUSB0 You should see the MicroPython REPL: MicroPython v1.8.7-7-gb5a1a20a3 on 2017-01-09; ESP module with ESP8266 Type "help()" for more information. >>>
  7. 9.

    Blinking the built-in LED >>> from machine import Pin >>>

    led = Pin(2, Pin.OUT) >>> for i in range(10): ... led.high() ... led.low() ... ... >>>
  8. 10.

    Code upload and execution • We will use adafruit-ampy •

    Installation: ◦ pip install adafruit-ampy • Set up the port connection: ◦ export AMPY_PORT=/dev/ttyUSB0 • Test it: ◦ ampy ls
  9. 11.

    Workflow • Edit your script main.py • Perform one-shot run

    and get console output: ◦ ampy run main.py • Upload the file to the board: ◦ ampy put main.py • Restart the board!
  10. 13.

    Schematics from machine import Pin button = Pin(0) if button.value():

    print("The button is not pressed.") else: print("The button is pressed.")
  11. 14.

    Connect to a WiFi import network def wifi_connect(ssid, pwd): """

    Connect to a wifi 'ssid' with password 'pwd' """ sta_if = network.WLAN(network.STA_IF) ap_if = network.WLAN(network.AP_IF) if ap_if.active(): ap_if.active(False) if not sta_if.isconnected(): print('connecting to network...') sta_if.active(True) sta_if.connect(ssid, pwd) while not sta_if.isconnected(): pass return 'IP address: %s' % sta_if.ifconfig()[0]
  12. 15.

    Post to Slack import urequests def to_slack(slack_hook_url, slack_icon_url, slack_message, slack_username):

    """ Send the 'slack_message' using an incoming webhook """ data = { "link_names": 1, "icon_url": slack_icon_url, "username": slack_username, "text": slack_message } res = urequests.post(slack_hook_url, json=data) return res.status_code == 200
  13. 16.

    Main loop (I) import time from machine import Pin if

    __name__ == "__main__": [...] led_pin = 0 # D3 button_pin = 12 #D6 wifi_connect(SSID, pwd) led = Pin(led_pin, Pin.OUT) button = Pin(button_pin, Pin.IN, Pin.PULL_UP)
  14. 17.

    Main loop (II) while True: # Button pressed if not

    button.value(): print("The button has been pressed") ok = to_slack(slack_hook_url, slack_icon_url, slack_message, slack_username) # If succeed, light the LED during 1s if ok: print("Succeeded posting to Slack") led.high() time.sleep(1) else: print("Failed trying to post to Slack") led.low() time.sleep_ms(10)
  15. 19.

    Main loop from machine import unique_id from ubinascii import hexlify

    from sht30 import SHT30 from umqtt.simple import MQTTClient [...] mqtt_server = "<YOUR_MQTT_SERVER_HOSTNAME>" mqtt_client_id = "micropython-{}".format(hexlify(unique_id()).decode()) print("mqtt_client_id:", mqtt_client_id) wifi_connect(SSID, pwd) client = MQTTClient(mqtt_client_id, mqtt_server) client.connect() sensor = SHT30() while True: time.sleep(1) temperature, humidity = sensor.measure() client.publish("{}/temperature".format(mqtt_client_id).encode(), "{:.2f}".format(float(str(temperature))).encode()) client.publish("{}/humidity".format(mqtt_client_id).encode(), "{:.2f}".format(float(str(humidity))).encode())
  16. 20.

    Notes • Get the driver dht.py from https://github.com/rsc1975/micropython-sht30 • Upload

    it to the board: ◦ ampy put sht30.py • Send the metrics to any MQTT broker ◦ iot.eclipse.org • Search for these topics: ◦ <mqtt_client_id>/temperature ◦ <mqtt_client_id>/humidity
  17. 25.

    The BBC Micro:bit It is an ARM-based embedded system designed

    by the BBC for use in computer education in the UK. • Size: approx. 5cm x 4cm • Weight: 8g • Processor: 32-bit ARM Cortex M0 CPU • Bluetooth Low Energy • Digital Compass • Accelerometer • Micro-USB controller • 5x5 LED matrix with 25 red LEDs • 2 programmable buttons • Powered by 2x AAA batteries
  18. 26.

    Using the REPL Install picocom and connect to the serial

    interface: picocom -b 115200 /dev/ttyACM0 You should see the MicroPython REPL: MicroPython v1.7-9-gbe020eb on 2016-04-18; micro:bit with nRF51822 Type "help()" for more information. >>>
  19. 27.

    Code upload and workflow • We will use uFlash •

    Installation: ◦ pip install uflash • Upload a script ◦ uflash main.py • Auto-upload when changes ◦ uflash --watch main.py
  20. 29.

    Built-in images from microbit import Image, display display.show(Image.HAPPY) HEART_SMALL HAPPY

    SMILE SAD CONFUSED ANGRY ASLEEP SURPRISED SILLY FABULOUS MEH YES NO TRIANGLE TRIANGLE_LEFT CHESSBOARD DIAMOND DIAMOND_SMALL SQUARE SQUARE_SMALL RABBIT COW MUSIC_CROTCHET MUSIC_QUAVER MUSIC_QUAVERS PITCHFORK XMAS PACMAN TARGET TSHIRT ROLLERSKATE DUCK HOUSE TORTOISE BUTTERFLY STICKFIGURE GHOST SWORD GIRAFFE SKULL UMBRELLA SNAKE...
  21. 30.
  22. 32.

    Music import music music.play(music.NYAN) music.play([‘c4’, ‘f#’, ‘g’]) DADADADUM ENTERTAINER PRELUDE

    ODE NYAN RINGTONE FUNK BLUES BIRTHDAY WEDDING FUNERAL PUNCHLINE PYTHON BADDY CHASE BA_DING WAWAWAWAA JUMP_UP JUMP_DOWN POWER_UP POWER_DOWN...
  23. 34.

    Compass import radio from microbit import display, Image, compass, button_a,

    button_b, sleep def menu_mode(): """ Principal menu mode """ while True: display.show(Image.HAPPY) radio.send("ready") if button_a.is_pressed(): send_direction() if __name__ == "__main__": radio.on() compass.calibrate() menu_mode()
  24. 35.

    Compass (II) def send_direction(): """ Send the direction which the

    probe is pointing to: direction_N, direction_NE, direction_E... """ display.show(Image.ARROW_N) while True: sleep(100) if button_b.is_pressed(): break # Back to the menu mode heading = compass.heading() if (heading > 337) or (heading <= 22): needle = "N" elif 22 < heading <= 67: needle = "NE" elif 67 < heading <= 112: needle = "E" [...] radio.send("dir_{}".format(needle))
  25. 36.

    Station import radio from microbit import display, Image def decode_direction(dirstring):

    """ Decode the dir_X and show the arrow """ needle = dirstring.split("dir_")[1] img = getattr(Image, "ARROW_{}".format(needle)) display.show(img) if __name__ == "__main__": radio.on() while True: incoming = radio.receive() if incoming is None: continue elif incoming.startswith("dir_"): decode_direction(incoming) elif incoming == "ready": display.show(Image.HAPPY)