97 An In­tro­duc­tion to Mi­croPython

The Python lan­guage has been made lean and fast to run on mi­cro­con­trollers. Be­gin­ners and ex­perts can use it to con­trol their elec­tron­ics projects with ease.

OpenSource For You - - Contents - By: Ayan Pahwa The au­thor works as an em­bed­ded soft­ware en­gi­neer at Men­tor Graph­ics (Siemens) and is also tech­ni­cal di­rec­tor and co-founder of SDIOT (Smart De­vices for IoT). You can view his re­cent con­tri­bu­tions at www.github.com/iayan­pahwa.

The Mi­croPython project is an open source im­ple­men­ta­tion of Python 3 that in­cludes a small sub­set of the Python stan­dard li­braries, and is op­ti­mised to run on mi­cro­con­trollers with con­strained en­vi­ron­ments like lim­ited ROM, RAM and pro­cess­ing power. It came about af­ter a suc­cess­ful Kick-starter cam­paign by Damien Ge­orge.

What is Mi­croPython?

Mi­croPython in­cludes the stan­dard Python in­ter­preter that runs on small em­bed­ded devel­op­ment boards. With Mi­croPython, you can write Python scripts to con­trol hard­ware. For ex­am­ple, you can make LEDs blink, com­mu­ni­cate with a tem­per­a­ture sen­sor, con­trol motors and pub­lish a sen­sor read­ing on the In­ter­net. It is worth not­ing that the firmware for such em­bed­ded de­vices is gen­er­ally coded in Assem­bly, C or C++, but us­ing Mi­croPython you can achieve al­most the same re­sults as with high level Python.

What Mi­croPython is not

Un­like the desk­top ver­sion of Python, Mi­croPython is a stripped down ver­sion for mi­cro­con­trollers; there­fore, it doesn’t sup­port all the Python li­braries and func­tion­al­i­ties. In the world of mi­cro­con­trollers, the firmware is di­rectly burned to the ROM (also known as pro­gram mem­ory), and there is no file system. Mi­croPython im­ple­ments a min­i­mal type of file system di­rectly on the Flash mem­ory of the mi­cro­con­trollers. If the de­vice has 1MB or more of stor­age, then it will be set up (upon first boot) to con­tain a file system. This file system uses the FAT for­mat and is stored in the Flash mem­ory by the Mi­croPython firmware. This gives users the ben­e­fit of be­ing able to ac­cess, read and write files within the main Python pro­gram for flex­i­ble stor­age op­er­a­tions.

There are two files that are treated spe­cially by the ESP8266 when it starts up: boot.py and main.py. The boot. py script is ex­e­cuted first (if it ex­ists) and once it com­pletes, the main.py script is ex­e­cuted. You can cre­ate th­ese files your­self and pop­u­late them with the code that you want to run when the de­vice starts up. boot.py gen­er­ally con­tains the boot pa­ram­e­ters, like whether to have se­rial de­bug­ging on or off, which Wi-Fi AP to con­nect, the main code to run, etc. Loop­ing stays in main.py, e.g., the logic for blink­ing LEDs.

It is also worth not­ing that mi­cro­con­trollers are gen­er­ally pro­grammed in C, wherein di­rect reg­is­ters are ac­cessed and ma­nip­u­lated to use the pe­riph­er­als of the mi­cro­con­trollers. The firmware code is cross-compiled and built for the tar­get mi­cro­con­troller ar­chi­tec­ture, and is flashed us­ing a suit­able pro­gram­mer. Mi­croPython ab­stracts all th­ese steps, but the con­straint here is the real-time fea­ture of mi­cro­con­trollers, in gen­eral. Hence, Mi­croPython is not suit­able for strict re­al­time ap­pli­ca­tions.

Boards sup­ported by Mi­croPython

There are nu­mer­ous boards/chipsets sup­ported by Mi­croPython, and more are ex­pected to do so in the near fu­ture as the project

ma­tures. The cur­rent board sup­port list is given be­low. py­board

This is the of­fi­cial Mi­croPython board, which comes with full Mi­croPython sup­port out-of-the-box. It fea­tures a STM32F405RGT6 ARM Cor­tex M4 based pro­ces­sor. Mi­croPython sup­ports APIs for al­most all hard­ware pe­riph­er­als of the chip like GPIO, i2c, SPI, UART, etc. ESP8266

Mi­croPython sup­port for the low cost Wi-Fi devel­op­ment ESP8266 mi­cro­con­troller is ex­cel­lent. Wi-Fi and In­ter­net ac­ces­si­bil­ity are made avail­able within Mi­croPython us­ing a spe­cial net­work li­brary. There’s also a Web-based REPL that al­lows you to run Mi­croPython code on ESP8266 by us­ing a Web browser within a lo­cal net­work.

BBC mi­cro:bit

This is a great new board that is aimed at teach­ing kids com­puter pro­gram­ming. With Mi­croPython on the mi­cro:bit, you can ac­cess the board’s pe­riph­er­als like LEDs, ac­celerom­e­ters, etc.

Note: The full list of sup­ported boards can be found at the Mi­croPython web­site.

Li­brary stacks sup­ported by Mi­croPython

Python sup­ports a va­ri­ety of li­braries on desk­top com­put­ers, but port­ing them di­rectly to a mi­cro­con­troller is not an easy task as they are not op­ti­mised for run­ning on ma­chines with less RAM. In­stead of mak­ing ex­ist­ing use­ful Python li­braries avail­able in Mi­croPython, they are stripped in or­der to be bet­ter op­ti­mised to run on con­strained hard­ware. The cur­rent li­braries sup­ported by Mi­croPython are named with the ini­tial u, which stands for the Mi­cro Li­brary im­ple­men­ta­tion: ucol­lec­tions – col­lec­tion and con­tainer types uhash­lib – hash­ing al­go­rithm uheapq – heap queue al­go­rithm uio – in­put/out­put streams uj­son – JSON en­cod­ing and de­cod­ing uos – ba­sic ‘op­er­at­ing system’ ser­vices ure – reg­u­lar ex­pres­sions usocket – socket mod­ule us­truct – pack and un­pack prim­i­tive data types utime – time re­lated func­tions uzlib – zlib de­com­pres­sion

Mi­croPython-spe­cific li­braries

Func­tion­al­ity spe­cific to the Mi­croPython im­ple­men­ta­tion is avail­able in the fol­low­ing li­braries. ma­chine — for func­tions re­lated to the board mi­cropython – to ac­cess and con­trol Mi­croPython in­ter­nals net­work — for net­work con­fig­u­ra­tion uc­types – to ac­cess bi­nary data in a struc­tured way

Li­braries spe­cific to py­board

The fol­low­ing li­braries are spe­cific to py­board: pyb — for func­tions re­lated to the board Time re­lated func­tions

Re­set re­lated func­tions

In­ter­rupt re­lated func­tions

Note: The full list of sup­ported li­braries can be found at the Mi­croPython web­site.

Load­ing Mi­croPython on an ESP8266 board

ESP8266 is a cheap Wi-Fi devel­op­ment board. Since Mi­croPython ex­poses all the re­quired APIs, in­clud­ing the net­work­ing stack, this chip is our pre­ferred choice for learn­ing how to load Mi­croPython. The ESP8266 raw chip

mod­ules re­quire a USB to TTL con­verter and a 3.3volt sta­ble power source to in­ter­act with the com­puter. Hence, we can use a com­plete ESP8266 board like NodeMCU or Adafruit Feather HUZZAH, which have all the nec­es­sary com­po­nents on the same board.

To flash the Mi­croPython firmware bi­nary on the ESP8266 board, a handy com­mand line tool known as es­p­tool can be used. It can be down­loaded di­rectly from the Python pack­age man­ager us­ing the fol­low­ing com­mands:

sudo pip in­stall es­p­tool

Check for the se­rial port af­ter con­nect­ing the board it is /

dev/tty.SLAB_USB­toUART in our case ls /dev/tty* can help you iden­tify it. es­p­tool.py --port “se­ri­al_­port” erase_flash es­p­tool.py --port “se­ri­al_­port” --baud 460800 write_flash --flash_­size=de­tect 0 “firmware_­file”

Here, the firmware file .bin should be kept in the cur­rent work­ing direc­tory:

iAyan:~ iAyan$ sudo es­p­tool.py --port /dev/tty.SLAB_USB­toUART erase_flash es­p­tool.py v1.2.1


Run­ning Ce­santa flasher stub...

Eras­ing flash (this may take a while)...

Erase took 10.8 sec­onds iAyan:~ iAyan$ es­p­tool.py --port /dev/tty.SLAB_USB­toUART --baud 460800 write_flash --flash_­size=de­tect 0 esp826620161110-v1.8.6.bin es­p­tool.py v1.2.1


Auto-de­tected Flash size: 32m

Run­ning Ce­santa flasher stub...

Flash params set to 0x0040

Writ­ing 569344 @ 0x0... 569344 (100 %)

Wrote 569344 bytes at 0x0 in 14.1 sec­onds (324.1 kbit/s)... Leav­ing... iAyan:~ iAyan$

Us­ing the se­rial REPL (Read Eval­u­ate Print Loop)

Just like flash­ing Mi­croPython to the board, its REPL can be ac­cessed over the se­rial port. Sim­ply con­nect your Mi­croPython com­pat­i­ble board, the ESP8266 board in this case, and it will mount as a Se­rial De­vice (COMMxx in Windows and /dev/ ttySiLabs in OSX and Linux). Use any se­rial emu­la­tor like Putty (on Windows), mini­com or screen on Linux/OSX to ac­cess the se­rial REPL, us­ing the baud rate 115200, as fol­lows: sudo screen /dev/tty.SLAB_USB­toUART 115200


sudo min­i­mum -D /dev/ttySLAB_USB­toUART

In Windows use Putty, for which the se­rial to be used is COMMxx (xx=COMM port num­ber un­der De­vice Man­ager) and baud rate is 115200.

If ev­ery­thing goes well, you will see the fa­mil­iar Python prompt, at which point you can write Python com­mands and view the im­me­di­ate out­puts. Type ‘print (“Hello World!”)’, and yes, it’s the same old Python that we love.

sudo screen /dev/tty.SLAB_USB­toUART 115200 “press en­ter”

>>> print("Hello, Mi­croPython!")

Hello, Mi­croPython!

>>> 2+5



Us­ing We­bREPL

One unique fea­ture of Mi­croPython on the boards which sup­port net­work­ing (like ESP8266) is a We­bREPL (read­e­val­u­ate-print loop, like a Python ‘com­mand line’) that is ac­ces­si­ble through a Web page. In­stead of us­ing a se­rial con­nec­tion to the board, you can run Python code di­rectly from your browser in a sim­ple ter­mi­nal. You don’t even need to con­nect the board to a Wi-Fi net­work; it can cre­ate its own net­work, which you can use to ac­cess the We­bREPL! The new re­leases of Mi­croPython come with We­bREPL dis­abled by de­fault; so use the fol­low­ing com­mands to en­able it over se­ri­alREPL:

>>> im­port we­bre­pl_setup

We­bREPL dae­mon auto-start sta­tus: dis­abled

Would you like to (E)nable or (D)is­able it run­ning on boot? (Empty line to quit)


To en­able We­bREPL, you must set pass­word for it

New pass­word: python

Con­firm pass­word: python

Changes will be ac­ti­vated af­ter re­boot

Would you like to re­boot now? (y/n) y

Once it’s en­abled, ESP8266 will start in AP mode and cre­ate a hotspot. You can con­nect to it with the pass­word mi­cropythoN and ac­cess We­bREPL us­ing the IP ws:// En­ter the pass­word that you’ve set ear­lier. The We­bREPL client can be ac­cessed by go­ing to http://mi­cropython.org/we­brepl/ or down­load­ing it via GitHub (https://code­load.github.com/mi­cropython/ we­brepl/zip/master).

Us­ing tools to make life easy with Mi­croPython Adafruit Mi­croPython Tool (Ampy): This is a util­ity to in­ter­act with a Mi­croPython board over a se­rial con­nec­tion.

Ampy is meant to be a sim­ple com­mand line tool to ma­nip­u­late files and run code on a Mi­croPython board over its se­rial con­nec­tion. With it, you can send files from your com­puter to a Mi­croPython board’s file system, down­load files from a board to your com­puter, and even send a Python script to a board to be ex­e­cuted. Down­load Ampy us­ing Python Pip.

sudo pip3 in­stall adafruit-ampy

Trans­fer files from PC to board us­ing Ampy and vice versa, as fol­lows:

ampy --port “se­ri­al_­port” put “file_­name.py” ampy --port “se­ri­al_­port” get “file_­name.py”

iAyan:~ iAyan$ ampy --port /dev/tty.SLAB_USB­toUART get boot.py # This file is ex­e­cuted on ev­ery boot (in­clud­ing wake-boot from deep­sleep)

#im­port esp

#esp.os­de­bug(None) im­port gc im­port we­brepl we­brepl.start() gc.col­lect()

iAyan:~ iAyan$ ampy --port /dev/tty.SLAB_USB­toUART put main.py iAyan:~ iAyan$ ampy --port /dev/tty.SLAB_USB­toUART ls boot.py we­bre­pl_cfg.py main.py This is handy to trans­fer main.py file to board which will run as board boots af­ter boot.py file.

Hard­ware tin­ker­ing with Mi­croPython

Hard­ware hack­ing - GPIO: Con­nect the pos­i­tive side, i.e., the an­ode of the LED to pin no. 15 on the ESP8266 board via a 330-ohm re­sis­tor and the neg­a­tive side or the cath­ode (the shorter leg) to the ground pin.

im­port ma­chine im­port time

pin_num­ber = 15 pin = ma­chine.Pin(pin_num­ber, ma­chine.Pin.OUT)

while True: pin.high() time.sleep(1) pin.low() time.sleep(1)

Net­work­ing with Mi­croPython

Net­work­ing is a pow­er­ful fea­ture of mi­cro­con­trollers to­day, thanks to the IoT era. ESP8266 is known to be a low cost Wi-Fi devel­op­ment board and, thanks to Mi­croPython, it ex­poses the re­quired APIs to ac­cess net­work­ing on the ESP8266 board.

Here’s a script to con­nect your board to your router and open the gate to the In­ter­net:

>>> im­port net­work

>>> AP_NAME = ““

>>> PASS­WORD = ““

>>> ap = net­work.WLAN(net­work.STA_IF)

>>> ap.ac­tive(True)

#5 et­s_­task(4020ed88, 28, 3fff9708, 10)

>>> ap.con­nect(AP_NAME, PASS­WORD)

>>> ap.if­con­fig()

(‘’, ‘’, ‘’, ‘’

Con­grat­u­la­tions! ESP8266 is now a de­vice on your lo­cal net­work with just five lines of Python code. Now you can ac­cess We­bREPL over this IP ad­dress.

Fig­ure 2: The Py­Board

Fig­ure1: Mi­croPython Kick-starter cam­paign

Fig­ure 3: ESP826

Fig­ure 4: BBC mi­cro:bit

Fig­ure 5: NodeMCU

Fig­ure 6: Screen­shot 1

Fig­ure 7: Screen­shot 2

Fig­ure 8: Screen­shot 3

Newspapers in English

Newspapers from India

© PressReader. All rights reserved.