Chapter 5 Micropython
Chapter 5 Micropython
..5-3
5.3.1.1 The Pyboard..
5.3.1.2 ESP32... ..5 -3
..5 - 5
5.3.4 Installing MicroPython on Different Hardware .
JENIL THAKKAR
5 MicroPython
Contents
5.1 Introduction
52 Diference between MicroPython and Python
5.3 Installation of MicroPython on Hardware
54 MicroPython Libraries
6.5 GPIO Programming on MicroPython Hardware
5.6 Sensor Programming
using MicroPython
(5- 1)
JENIL THAKKAR
Python Programming 5-2
icroPython
5.1 Introduction
MicroPython includes the standard Python interpreter that runs on small embedded
development boards. With MicroPython, you can write Python scripts to control
hardware. For example, you can make LEDs
blink, communicate with a temperature
sensor, control motors and publish a sensor
reading on the Internet. It is worth noting
that the firmware for such embedded devices is
generally coded in Assembly, C or C++,
but using
MicroPython you can achieve almost the same results as with high level
Python
5.2 Difference between MicroPython and Python
Unlike the desktop version of Python, MicroPython is a
stripped down version for
microcontrollers; therefore, it doesn't support all the
Python libraries and functionalities.
In the world of
microcontrollers, the firmware is directly burned to the ROM (also known
as
program memory), and there is no file system.
MicroPython implements a minimal
type of file system directly on the Flash memory of the microcontrollers. If the device has
1 MB or more of
storage, then it will be set up (upon first boot) to contain a file
This file system.
system uses the FAT format and is stored in
the Flash memory by the
MicroPython firmware. This gives users the benefit of
being able to access, read and write
files within the main Python
program for flexible storage operations.
5.3 Installation of MicroPython on Hardware
MicroPython is a compact implementation of the Python 3
programming
designed to work with microcorntrollers. Initially announced back language
in 2013 as part ot a
Kickstarter project created by Damien George,
MicroPython eventually became one ot the
preferred firmware options for microcontroller programmers and enthusiasts
Damien ended up created his own line of
alike
hardware that comes equipped wiu
MicroPython right off the bat. However, the firmware can also be installed on a wiae
range of other boards.
If you're interested in
making a career out of hardware programming or simpiy want
to do it as a hobby, you'l have a lot to
gain by learning how to work with MicroPython
with MicroByu
In this beginner's guide, we're going to teach re
you the basics about compatible haraw
and workflow, as well as show you a couple of practical examples or w
JENIL THAKKAR
for knowledge
5-3
PpthonProgramming
MicroPython
631MicroPython Hardware
53.12 ESP32
ESP32 is a high-performance, low-cost series of microcontrollers that come with a wide
variety
of features, including built-in Wi-Fi and Bluetooth capabilities. The specs include
520 KSRAM
and a CPU clocked at either 160 or 240 MHz, depending on the model. The
ESP32 DOards are quite powerful for their size and feature lots of extras like power
magement modules, antenna switches, power amplifiers, filters, and more.
Though the price of the chip itself is quite affordable, you may have to purchase the
avarious modules separately and there are many to choose from. Not necessarily the best
choice
ginners,but
ib done. if you know what you're doing, the ESP32 can definitely get the
If
you'
mayrewant
eatures, you1ay looking for cheaper option
a and don't mind out on some
missing
to check out ESP32's predecessor, the ESP8266 series.
JENIL THAKKAR
Python Programming 5-4
AicroPython
accelerometer, Bluetooth connectivity, microUSB, two programmable buttons. ed
connector, and more. The Micro : Bit is aimed at children between the ages of 7 and dge
but you
14
can
definitely made good use of the board even if you're a lot older.
5.3.2 CircuitPython
CircuitPython is a project that's quite similar to MicroPython in the sense that it was
also designed to make hardware
programming as simple and as accessible as possible.
CircuitPython is fully compatible with the Pyboard, as well as a wide variety of other
microcontrollers, including a number of boards developed by
open-sOurce hardware
company Adafruit. The company's flagship board goes by the name of
Circuit
Playground Express and comes equipped with all of the features a beginner needs to
started with hardware get
programming. A few of the highlights include motion sensor,
temperature sensor, mini speaker with class D amplifier, infrared receiver, RGB
USB port, and more. LEDs,
mder, Terminus,
o t r y ,i n c h u d i n g C m d e Xshell, and of course, PuTTY, which is the
go-to
users.
most
for
Ogram
EPL connectionis established, you can enter and execute commands
CnceyourR E
using
oneactivempt. MicroPython's REPL was designed with accessibility in mind and
prompt. Mica
the
interact
a8
S u c hi n c h u d
some very useful features like tab completion, paste mode, history, auto-
i n d e n t ,a n d m o r e .
332Command-Line Tools
vboard.py is a
standalone
one tool that lets you run Python scripts or commands on a
Dthon device and inc
levice and includes a few other neat features. While the tool was designed
MicroPython
ith
w
the Pyboard, it's also compatible with other microcontrollers that support
towork
ow REPL. This includes the ESP32 and ESP8266 series, which we mentioned in
ion 5.3.1.2. A few other useful command-line tools you may want to try are RShell,
section
Upvdev, and Ampy.
JENIL THAKKAR
TECHNICAL PUBLICATIONS- An up thrust for knowledge
Python Programming 5- 6
Probably the easiest way to get MicroPython on your board is to use the MicroPython
You can potentially get a two-for-one deal here because the Craft Tm
uPyCraft IDE.
application can also be
1scod
to program boards,
though ie's primarily optimized for ESP32 and ESP8266 ised
variants Tu
steps for installing MicroPython using uPyCraft are as follows: The
1. Start by installing the software on your computer and then
go to the oficial
MicroPython website to download the correct firmware for
Connect your microcontroller to your particular board,
2.
your computer and
proceed to the next step.
Open uPyCraft and go to Tools -> Boards. Select the
example, if you're using an ESP32-based board,appropriate option from the
list. For
options labeled as "esp32". If your board is you should see one of the
list, make sure your USB connected but don't you see it on
drivers are the
3. Access the Tools menu up-to-date.
again, but this time select the
new window will
appear where you can customize the
option "BurnFirmware". A
an ESP32
microcontroller, you'll want to choose the installation. If you're using
board: esp32 following options:
burn_addr: Ox1000
erase flash: yes
com: COM5
Some of these
options may differ depending on
documentation if you're your board, so make sure to
using a different check tne
4 Your next order
of business is
microcontroller.
to
choose the firmware
"Firmware Choose," select you want to install.
the "Users"
Navigate to the Downloads folder option and then click the "Choose" Dnuc
downloaded earlier. to find and buttol
select the
5.5. Hold down the yo MicroPython file you
BOOT button
microcontroller and, at the (name may differ depending onn your board)boara) on your
window. Once the same time, your
The firmware installation click the "OK" button in the uy at
installation process starts, you can release the BOOT button.
good to start should only take a few Do
Example of Installing programming your board. seconds, after whichyou shouldbe
you s
MicroPython is MicroPython
port of the a
inexpensive microcontrollers. Python
on an In this programming
ESP8266-based you will learnlanguage
ng language that runs on small,
the section, that
ESP8266 NodeMCU microcontroller such as the how
insia to install MicroPython
sections, you will using Adafruit SP8266 a
uzzah ESP826 and
learn how to Python and a Feather Huzza
control an LED package
and
called
espresptool. In subseqi
uent
read a sensor
Python
sensor usingMicroPython. The
TECHNICAL
PUBLICATIONS- thrust An up
for
knowledge
JENIL THAKKAR
5-7
t h o nP r o g r a n m m u i n g
MicroPython
following ardware
hardware is needed to install
MicroPython on an ESP8266-based
microcontroller:
MicroPython
firmware .bin file Version of MicroPython run on the
microcontroller
Summary of Steps
Install the Anaconda distribution of Python
Create a new conda environment and pip install esptool
Download the latest MicroPython .bin firmware file
nstall the SiLabs driver for the Adafruit Feather Huzzah ESP8266
5. C
Loninect the ESP8266-based microcontroller board to the laptop using a micro USB
cable
6. Determine v
Eermine which serial port the microcontroller is connected to
. Run the esptoo microcontroller
8.
neesptool to upload the .bin firmware file to the
Download and install PuTTY, serial monitor a
9.
and commands at the
se PuTTY to connect to the microcontroller run
MicroPython REPL.
3.5 Install the Anaconda Distribution of Python
you ont
don't have
have the Anaconda distribution of Python installed already, go to
Anac
naconda.com/down to download and install the latest
version.
JENIL THAKKAR
TECHNICAL PUBLICATIONSAn up
thrust for knowledge
Python Programming 5- 8
icroPython
1. Create a new conda environment and install esptool
To install MicroPython on the ESP8266-based microcontroller, we will start by creatinng
a virtual environment. A virtual environment is arn isolated
Python interpreter and a set
of packages that are
separate from the base version of Python running on your computer
We'll create a new virtual environment with the Anaconda
Prompt and the conda
command line tool.
Open theAnaconda Prompt and create a new virtual
environment named
micropython. Activate the environment with the command conda activate. After
activating the virtual environment, you should see the virtual environment name
(micropython) before the> Prompt. Once inside the virtual environment, use pip to install
esptool. esptool will be used to upload the MicroPython .bin firmware file onto
the
ESP8266-based microcontroller. Confirm that
esptool is installed in the (micropython)
virtual environment
by running the command conda list. The list of commands below
also creates a new
directory in the Documents folder called micropython
to store all the
project files.
>conda create -n
micropython python=3.6
>conda activate micropython
(micropython) > pip install esptool
(micropython) > conda list
(micropython)> cd Documents
(micropython)> mkdir micropthon
(micropython) > cd micropython
TECHNICAL PUBLICATIONS- An
JENIL THAKKARknowledge up thrust for
Python Programming 5- 9
********
..
**nnsmennnens..
***********************"
**************************************** *t **
MicroPython
***************************** *****
*****""**********************************************************
iceother-Python i x
-
***** ***********
*****
**** ****'**************
mcFoDython.0g iad/*asD6
..... ************
a..................
****** **********
S
SILICGN LA8
.
JENIL THAKKAR
TECHNICAL PUBLICATIONS®- An up thrust for knowledge
5- 10
Python Programming MicroPython
4. Connect the ESP8266-based microcontroller to the computer
Use a microUSB cable (the same kind of cable that charges many mobile phones) to
connect the ESP8266-based microcontroller to the computer. Make sure the microUSB
cable is a full USB data cable and not just a power only cable. If you have trouble getting
the microcontroller to work, one reason might be the micoUSB cable you are using is only
a charging cable and can not transfer data.
Use the Windows Device Manager to determine which serial port the ESP8266-based
mirocontroller is connected to. The serial port is one of the parameters which needs to be
defined when the .bin firmware file is upload on the board.
Look for something like Silicon Labs CP210x USB to UART Bridge (COM4) in the
Ports (COM & LPT) menu of the Windows Device Manager. TCP210x USB to UART
Bridge refers to the chip that handles serial communication on the board, not the ESP8266
chip itself. Make a note of the number after (COM). The serial port number often comes
up as (COM4) but it may be different on your computer.
Fiters s
Best natch
DeEe Aanager
Search suggestions
SGevice managen
JENIL THAKKAR
TECHNICAL PUBLICATIONS An up
thrust for knowledge
5-11
MicroPython
/1oe
Anager
STesy Help
www.***** ****
DESA
TOP 10YNOC
cutputs
inpUs
end
Audhe
Roltenes
Fivetecth
Compute
Dst de
D s l a ya 5 d e p t e r s
eICEs
H u m e nIntefoce Devn
Aeboards devices
pointing
cther
end
Mice
T Monitos
Netvcrk sdapters
Precessots
S Dhost edepters
Software devices
controliers
vadec 2n5 game
Scund,
Storage controliers
System devices
controllers
Seriel Bus
Universl
****************-******* **
******************** **********************************
********** ******************.*
ESP8266-based microcontroller
the .bin file to the
&Runesptool to upload Start Menu and cd(change directory)
Open the Anaconda Prompt with the Windows
to see
directory which contains the .bin file. Use the dir command
ito the micropython
contents. Make sure the .bin firmware
file is in the directory.
he micropython directory
like esp8266-20171101-v1.9.3.bin. Activate the
The bin firmware file is named something
command conda activate micropython. Run
mixopython virtual environment with the
Note there is no .py extension after
sptool-help to ensure esptool is installed properly.
command esptool.py may
ool. On Windows, the command esptool works, but the
on the MicroPython docs).
D [Note this behavior is different than the commands shown
y y to run esptool and you are not in the (micropython) virtual
environment, an
eor is returned.
od Documents
od mictopython
pwd
oouments/micropythona
> dir
Before uploading the .bin firmware file to the ESP8266-based microcontoller, it is best
practice to first erase the flash memory on the board using the command esptool
erase flash. Make sure to specify the -port. The argument after -port is the COM port
assigned to the ESP8266 board shown in the Windows Device Manager. This port oftern
comes up as cOM4.
(micropython) > esptool --post cOM4 erase_lash
the
Now you can finally write the .bin firmware file to the flash memory
microcontroller using the esptool write_flash command. Make sure to use ot
set
to
needs
nrmware file name you see sitting micropython directory. The port
in the
is the
---baut
COresponding to the port you found in the Windows Device Manager. ecify
baud rate or upload worked, but you couda
speed. I found that -baud 460800 baud
-baud 115200 which is slower. The upload time was a matter of seconds witn c the
rate. The 0 after -flash_size = dectect means the firmware is written at tne
file
firmware
flash memory (the 0th position) on the board. Again, make ssure the .bin
u r e the .bin n
C:
. Users\ PhP \Documents
Users opythonesptool -port COWA-baud 460800
thon-flash_size=detect e espë266-20171181-v1.9.3.bin
enogpy
i t e _
FIash
that
MicroPython is installed on the ESP8266-based microcontroller, we can
Now
PuTTY
lightweight seria and SSH client for Windows. PuTTY provides an
is a
dowmload and
installation are quick.
and the
X
**********************************-***--*..
. ***** . * .. .................... ..... .... .... ... .. ..... . ... .. .. .... ..... ..-.
Download PuTTY
****
w**
PuTTY IS an SSH and teinet client, ceveloped originaily by Simon Tatham for
....,
.
the Windows piatform. PuTTY is open source seftware that is avaliabie with
source code and is deveioged and supported by a group of volunteers.
ss*******************************************************************'**********************************************************************"|
.* * * * * * * * * * * * * * * * * * * * * ** * *
** ** **** **
***
radio button below the header Connection type : Near the top of the PulTY
window. Overlooking this detail is easy.
OneNote 2015
QOutook 2016
Puine2 0
People
PPowertont 2
Pageant
New
PatTY Man
PuTTY Web Site
PutYgen
ew
JENIL THAKKAR
AARonP r o g a m m i n g
5-15
*** ARAA*AAMamNARAAAMAnAN
**AaAAMAAASNaAAAAANAAAnMAAAAAAtmAMAAAAA***AAAA***
MicroPython
PuTTY Configuration
wwwwwwwwwwwwwww. session
Loggng Specty the destirnation yoi wart to connect
Teninat to
Senal ine
Keyboard ****** ***wwwwwwwwww
Speed
CON
Be ************************************* 115200
Features Cornectior? type:
Window Ra OIeinetRilognOSSH Segal
****
Appearancee
Load. save or deiete a stored ses9io
Behaviour
Translation
Selection
*********** ******wwwwww.ww.wwwwww ***********wwwwwv
Coiours *********************
Lefaut Setngs
** ***********************************
Data
aye
Proxy
Telnet
Riogin *******************************.**
Sers
ose window an ext
Aways ever Only on clear ext
****************
******************
**
Hpout * ***************************************
**********************w*
*wwww.wr w**********************************
********rvr**rvo*********ereo.
you see >>» the MicroPython REPL (the MicroPython prompt), MicroPython is
Sometimes, you ma
nay need to type [Enter]
or Ctrl-D to bring up the > > REPL orompt.
i the PuTTY window, try to close PuTTY,
AL
Prompt is not displayed in your
unplug then replug the board and open PuTTY again.
Most ESP8266-based
**
************** ****************************** X
CO4- PuTTY
SETT et ask{40109130, 3, 3fff831c, 4)
ETror Errno 23ENOENT
module with ESP8266
croPython
ype () v1.9,3-8
Eor 9,3-8-g63826acsc
on
2017-11-01:
ESP
OTE information.
COM4 - PuTTY
x
ets taski40100130, 3, 3fft837C
OSError: [Errho 2} ENOENT
libraries.
-
For functic
related to the board
machine
micropython
To access and control MicroPython internals
network configuration
.
network-For
uctypes-
To access binary data in a structured way.
to pyboard
Loraries specific
libraries are specific to pyboard:
Thefollowing related to the board
pyb-for functions
Time related functions
Hardware
55 GPIO Programming on MicroPython can be used to perform
A GPIO is a integrated circuit or board that
signal pin on an
and can be used
functions. By design it has no predefined purpose
igital input output
or
the functions they choose. Typical
or software developer to perform
ye nardware switches and controlling
various types of
Ppications include controlling LEDs, reading
ensors.
GPIO connector that
have a 40-pin
tmodels of Raspberry Pi, for example,
PTOVides access to about 25 GPIO ines.
wwwrmit
JENIL THAKKAR
for
PUBLICATIONS- An up thrust knowledge
TECHNICAL
5-18
Python Programming MicroPython
The most common functions of GPIO pins include:
Being configurable in software to be input or output
JENIL THAKKAR
TECHNICAL PUBLICATIONS An up thrust
for knowledge
Python Programming 5-19
MicroPython
3.3V
1
oD out
S2
Dout Round|2x Vi
Vrei)
Wnere B is the number of bits of the ADC, e.g. 12 for the ESP32.
ne
attn(arg) function is used to set the reference voltage V to one of the values
Table 5.5.1.
Configuration parameter
ADC.ATTN ODB 1.1 V
ADC.ATTN25DB 1.3 V
JENIL THAKKAR
TECHNICAL PUBLICATIONS- An up thrust for knowledge
Python Programming 5-20
ample 5.5.1 Set ADC full seale range to 1.1 V (with "Loboris MicroPython"
MicroPython
adcO.rend
returnsthe ADC input in milli-Volts)
Solution
fromboardimportADCO0
frommachineimportPin, ADC
adc0=ADCPin(ADCO))
2000 *************************sow*gn*or****w*
O dB
1000 ****************** ************ ********************************vwwv** ******************:***
w2.5 dB
w**wwww 6 dB
**** 11 dB
TECHNICAL
JENILPUBLICATIONS-An
THAKKAR for knowledge up thrust
Python Programming 5- 21
MicroPython
ESP32 ADCO offset: Code vs
Vin near zero
30 ***w*ww*wwvwww
. 0 dB3
*******Vv***ww**ww*www******owwwwww.wwwweewte**nn
25
wwwww
2.5dB *****************
* ** *********************************************
www.ww 6 dB
20 .11 dB *******************
*********?**************
*********************************
*********************
*****************************************
***************************************************************** * * * * * * **
** * * *
10
*********************
******************************* ****************
*** *************************
*******
****************************************** ********
www.
******o000o ww ***********************
0 20 40 60 80 100 120 140 160
Vin M
* ****** ***
************ ***************
25 ******* ****
JENIL THAKKAR
TECHNICAL PUBLICATIONS -An up thrust for knowledge
Python Programming 5-22
None
12
Ethernet MAC
Interface
None
Touch Sensor
14
None es
Temperature Sensor
15 None Yes
Workin8 Temperature
-40 °C-125 °C 4 0 °C 125 °C
Table 5.6.1
MemoryError issues
You can usually get the following error
using MicroPython
Memory
allocation failed,
allocating xxxx bytes. The MemoryErcially
RAM is very limited,
yError:
the
especa
JENIL
TECHNICAL THAKKAR
PUBLICATIONS An up thrust
-
for knowledge
Python Programming 5 23
nd some
ESP&266 and sometimes on the ESP32-VWROOM. MicroPython
If you run into this issue, you can cross-
Compile the python files that you want load to the board to reduce the RAM
Tadothat, you need to use Linux (Sorry Windows use.
users) and clone the
WiPy: pycom/pycom-micropython-sigfox repositories
ESP32/ESP8266: micropython/esp32
Then, go to the folder mpy-cross
using a terminal, and type make.
seconds/minutes. Then, you can compile the python files Wait a couple of
to get the mpy files. using /mpy-cross <filename.py>
Then, load only the .mpy files not the
.py files! Otherwise, the board tries
py and you get the same error to load the
again.
For the Code of Sensor
Code Visit
https://github.com/lemariva/uPySersors
because it may use so
many files so it is not
possible to show in book.
But for
your understanding I have given one example on Sensor
Temperature Sensor
There are
many temperature the market. One
sensors on
the MCP9808 breakout board from well-documented sensor is
Adafruit. Like our light sensor, it uses the
Communication. To use the sensor, IC2 bus for
.
Power and ground can
you need four connections
:Ground, power, SDA, and
be connected to the
EACDOard or power and ground lines of
you can
directly to the associated
pins on the ESP8266. For
the SDA and SCL
your
either connect them pins,
nes) through the
directly to the ESP8266 or daisy-chain them
Lux sensor. Assuming (connect in
your you already have the TSL2591 sensor
ESP8266,
here are the connections you will need wired to
JENIL THAKKAR
TECHNICAL PUBLICATIONS- An up thrust for knowledge
5-24
Python Programming MicroPython
ThingFlow for MicroPython has a sensor class for the MCP9808 cated
in
micropython/sensors/mcp9808.py. Here is an example MicroPython REPL session th
re
we sample both the lux and temperature sensors using ThingFlow:
>>>fromts12591 importTs12591
>>>frommcp9808importMcp9808
>>>lux=Ts12591()
>>>temperature =Mcp9808()
Read manufacturer ID: 0054
Read device ID: 040o
>>>sched=Scheduler)
>>>sched.schedule_sensor(lux, 10,Output())
<closure >
>>>sched.schedule_sensor(temperature,10,Output())
<closure>
>>>sched.run forever()
(ts12591, 108, 162.221)
(mcp9808, 108, 26.1875)
(ts12591, 117, 162.221)
(mcp9808', 117, 26.1875)
(ts12591, 126, 1.5096)
('mcp9808, 126, 26.1875)
JENIL THAKKAR
TECHNICAL
PUBLICATIONS- An up thrust
for knowledge