Micropython For Microcontrollers 1st Edition Gnter Spanner PDF Download
Micropython For Microcontrollers 1st Edition Gnter Spanner PDF Download
https://ebookbell.com/product/micropython-for-
microcontrollers-1st-edition-gnter-spanner-50751504
https://ebookbell.com/product/python-for-microcontrollers-getting-
started-with-micropython-donald-norris-42922654
https://ebookbell.com/product/micropython-for-the-internet-of-things-
a-beginners-guide-to-programming-with-python-on-microcontrollers-
charles-bell-38548020
https://ebookbell.com/product/micropython-for-the-internet-of-things-
a-beginners-guide-to-programming-with-python-on-microcontrollers-
charles-bell-58183410
https://ebookbell.com/product/micropython-cookbook-over-110-practical-
recipes-for-programming-embedded-systems-and-microcontrollers-with-
python-alsabbagh-22965632
Micropython For The Internet Of Things 2nd Edition 2nd Charles Bell
https://ebookbell.com/product/micropython-for-the-internet-of-
things-2nd-edition-2nd-charles-bell-55897704
https://ebookbell.com/product/micropython-for-the-internet-of-things-
charles-bell-35147354
https://ebookbell.com/product/micropython-for-esp32-development-
workshop-agus-kurniawan-44857388
https://ebookbell.com/product/micropython-for-everyone-how-to-use-
esp32-and-esp8266-micropython-arduino-donelan-23641802
https://ebookbell.com/product/micropython-for-everyone-how-to-use-
esp32-and-esp8266-micropython-arduino-lamont-donelan-33187128
books
MicroPython for
Microcontrollers
Projects with Thonny-IDE, uPyCraft-IDE, and ESP32
Günter Spanner
MicroPython for Microcontrollers
Projects with Thonny-IDE, uPyCraft-IDE, and ESP32
Dr Günter Spanner
● This is an Elektor Publication. Elektor is the media brand of
Elektor International Media B.V.
PO Box 11, NL-6114-ZG Susteren, The Netherlands
Phone: +31 46 4389444
● All rights reserved. No part of this book may be reproduced in any material form, including photocopying, or
storing in any medium by electronic means and whether or not transiently or incidentally to some other use of this
publication, without the written permission of the copyright holder except in accordance with the provisions of the
Copyright Designs and Patents Act 1988 or under the terms of a licence issued by the Copyright Licencing Agency
Ltd., 90 Tottenham Court Road, London, England W1P 9HE. Applications for the copyright holder's permission to
reproduce any part of the publication should be addressed to the publishers.
● Declaration
The Author and the Publisher have used their best efforts in ensuring the correctness of the information contained
in this book. They do not assume, and hereby disclaim, any liability to any party for any loss or damage caused by
errors or omissions in this book, whether such errors or omissions result from negligence, accident or any other
cause.
Elektor is part of EIM, the world's leading source of essential technical information and electronics products for pro
engineers, electronics designers, and the companies seeking to engage them. Each day, our international team develops
and delivers high-quality content - via a variety of media channels (including magazines, video, digital media, and social
media) in several languages - relating to electronics design and DIY electronics. www.elektormagazine.com
●4
Content
Chapter 1 • Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.2 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Chapter 3 • P
rogramming and Development Environments . . . . . . . . . . . . . . . . . . 19
4.10 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
●5
MicroPython for Microcontrollers
●6
Content
9.12 Data power: multi-sensor array with the DS18x20 thermal sensor . . . . . . . . . . 110
9.16 No more dents and scratches: distance warning device for garages . . . . . . . . . 119
10.3 The exact time please: digital clock with OLED display . . . . . . . . . . . . . . . . . . 140
●7
MicroPython for Microcontrollers
16.3 Data for the smartphone with the ThingView app . . . . . . . . . . . . . . . . . . . . . . 195
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
●8
Notices and Disclaimers
2. The circuits in this book may only be operated with batteries and/or tested, dou-
ble insulated safety power supplies. Insulation faults of a simple power supply
unit can lead to life-threatening voltages on non-insulated components.
3. Powerful LEDs can cause eye damage. Never look directly into an LED!
4. Neither the Author or the Publisher accept any liability for damage resulting from
the construction of the described projects, or attempts to do so.
●9
MicroPython for Microcontrollers
The demo programs mentioned in this book can downloaded free of charge as a single ar-
chive file (.zip) from the book resources web page:
www.elektor.com/micropython-for-microcontrollers
If a program from the download archive file appears to differ from the version described in
the book, the downloaded version should be used as it may reflect updates made by the
author since printing the book.
● 10
Chapter 1 • Introduction
Chapter 1 • Introduction
The introduction of the ESP32 chip from Espressif Systems marks a new generation of
microcontrollers, which offer excellent performance, Wi-Fi, and Bluetooth functionality at
an unrivalled price. These features have taken the maker scene by storm. The most diverse
applications and projects in the areas of Internet of Things (IoT) and home automation can
be implemented easily and cost-effectively. The ESP32 is as easy to program as the classic
Arduino boards. In comparison, however, the ESP32 also offers, among other things:
For these reasons, it can be considered the most promising successor to Arduino. The term
"Arduino killer" is often used in this context.
This book introduces the programming of modern single-chip systems (Systems on Chip —
SoCs). In addition to the technical background, the focus is on the programming language
Python, especially in its variant "MicroPython". Basic relationships between electronics and
electrical engineering will only be dealt with to the extent that it is essential for the design of
the circuits and experiments.
The "hardware" for getting started can be kept very simple anyway. At first, only a controller
board and some light emitting diodes as well as suitable series resistors are required. The
PC or laptop required for programming the chip should be available in every household. The
appropriate programming environment can be downloaded free of charge from the internet.
When working with a MicroPython programming environment, however, the first problems
quickly arise. A good introduction can therefore lead to excellent performances.
Python has experienced an enormous upswing in recent years. Various single-board systems
like the Raspberry Pi have especially contributed to its popularity. But Python has also found
widespread use in other areas such as artificial intelligence or machine learning. Hence it
is a logical choice to use Python or the variant MicroPython for the application in SoCs, too.
However, we will not restrict ourselves to a mere introduction to the programming lan-
guage. In many cases, the learned programming skills are put into practice together
with electronic circuitry. The fully described projects are all suitable for use in laborato-
ries or in everyday life. In addition to the educational effect, the pleasure of assembling
complete and useful devices is therefore also in the foreground. Through the use of lab-
oratory plug-in boards, circuits of all kinds can be realised with little effort. The testing
● 11
MicroPython for Microcontrollers
Due to the various applications such as weather stations, digital voltmeters and function
generators, the presented projects are also ideally suited for internships or study courses in
the natural sciences or in science and technology lessons.
MicroPython is relatively new. The user community is growing, and more and more platforms
are supported. MicroPython is essentially a slim version of Python, one of the most popular
programming languages in the world. Therefore, specific problems can be dealt with not only
in MicroPython communities. In fact, general Python forums are increasingly contributing to
solving MicroPython issues.
In addition to community support, MicroPython also has certain features that put it well
above the class of the Arduino. One of these features is the so-called REPL function. REPL
stands for "Read-Evaluate-Print Loop". This allows programs and code sections to be execut-
ed quickly. Compiling or uploading is not necessary. In this way, parts of a code can be tested
quickly and efficiently during development.
1.2 Requirements
In order to work successfully with this book, the following requirements should be met:
For specialized knowledge in the field of electronics, please refer to the extensive technical
literature, especially from Elektor, through their books, magazines, and kits. The hardware
● 12
Chapter 1 • Introduction
structure was deliberately kept simple, as the focus should be on programming with MicroPy-
thon. Nevertheless, different components and parts are required. Explanations can be found
in the individual chapters in which the components are used first. In addition, the last sec-
tions of the book explain some basic components such as resistors or light emitting diodes.
You can consult these if there are any unclarities concerning individual components.
It is also useful to employ an active USB hub between the computer and the controller. This
has the advantage that it guarantees a certain protection for the PC. The hub should have
its own 5 V power supply through a separate power supply unit. Then the PC or laptop is best
protected against short-circuits behind the hub, as it is very unlikely that a short circuit will
"blow through" an active hub to the USB port of the computer.
● 13
MicroPython for Microcontrollers
The ESP32 is a modern and extremely powerful microcontroller. In addition to a high clock
frequency and the extensive internal functional units, the chip has integrated Wi-Fi and
Bluetooth. The controller was developed by Espressif Systems, a Chinese company based
in Shanghai, and is enjoying increasing popularity. The performance features of the ESP far
exceed the well-known Arduino boards in terms of price and performance.
As the ESP32 is only available as an SMD chip, a so-called break-out board (BoB) or devel-
opment board is required if the controller is to be used in a non-professional environment.
In the meantime, a virtually unmanageable variety of different versions is available on the
market. The best-known versions are:
These boards have the necessary prerequisites to operate the ESP controller on a solderless
plug-in board or breadboard. Frequently, in addition to the controller, other components
such as pushbuttons, a Li-ion battery charger, or various LEDs are mounted on the boards
● 14
Chapter 2 • A Variety of ESP Boards
available. This means that initial tests and experiments can be carried out without external
circuitry.
The following section summarizes the most important data about ESP32. The overview
should only provide a first impression. A deeper understanding of the individual features
and functions is then provided in the relevant sections in the book.
The ESP32-PICO-KIT is usually employed for the application examples in this book. Alter-
natively the ESP32 DEV KIT or another board can be used. The variant used is mentioned
explicitly in each case. In principle, however, the various boards are largely compatible. They
differ mainly in size and in pin arrangement order. Figure 2.2. shows the PICO-KIT with its
functional units and connections.
● 15
MicroPython for Microcontrollers
The breakout boards are best suited as experimental and development boards. Via the port
connections, electronic components such as LEDs, temperature sensors or even smaller ac-
tuators such as R/C model servos can be connected directly. The Pico Kit board has the fol-
lowing features, among others:
On most boards, an LED will light up when connected to a powered USB port. If, contrary to
expectations, this so-called "power-on" LED does not light up, the USB connection should be
disconnected immediately. In this way you can prevent a possible short circuit from causing
major damage. For further troubleshooting, helpful hints are given in the corresponding
chapter at the end of the book.
ESP boards should always be operated in a solderless plug-in board (see Figure 2.3). How-
ever, if you do work without a breadboard, make sure that the base used is not conductive,
● 16
Chapter 2 • A Variety of ESP Boards
otherwise short circuits between the pins may occur. Next to the ESP board itself, this can
even destroy the USB port of the PC.
If a direct data exchange with the PC is no longer necessary, the board can also be supplied
by a USB power supply. This should be able to supply at least 1,000 mA (1 A; 1 amp) of
current output to avoid unwanted voltage drops. In addition, there is a certain amount of
reserve power to operate some LEDs, displays or sensors.
Even without a USB connection, the board can send and receive data via Wi-Fi and Blue-
tooth. In order to achieve complete independence from power and data cables, the module
then only needs to be powered by (rechargeable) batteries.
Some boards have a Lithium-Ion (Li-Ion) battery connector for this purpose (see Figure 2.4).
There, suitable cells can be connected directly via the standard plug. An internal voltage
regulation then ensures that the controllers are optimally supplied. In addition, a connected
battery is charged as soon as the board is connected to a live USB socket.
For this application, cells with a capacity of about 1,500 mAh or more are suitable. Smaller
batteries below 300 mAh should not be used, as they could be overcharged by the integrated
charge controller.
With a typical power consumption of approx. 50 mA, the 1,500 mAh variant can achieve an
operating time of around 30 hours, i.e. just over a day. When using the controller's sleep
functions, even considerably longer operating times can be achieved.
● 17
MicroPython for Microcontrollers
Single cell LiPo (Lithium Polymer) or Lithium-Ion batteries provide sufficient power for the
ESP32. However, their voltage of 3.7 to 4.2 V, depending on the state of charge, is too high
for the ESP32. It is therefore regulated down via an internal module.
As working with Li-ion batteries is always associated with a certain degree of danger, the
following information should not be omitted:
● 18
Chapter 3 • Programming and Development Environments
Chapter 3 • P
rogramming and Development
Environments
Unlike the situation with, say, an Arduino system, there are several Integrated Developing
Environments (IDEs) available for working with MicroPython. In principle, you can write pro-
grams with all IDEs and load them onto the controller. The two most widespread program-
ming environments are currently:
• µPyCraft
• Thonny
Both have their own specific advantages and disadvantages. The differences lie mainly in the
different procedures for developing and managing program code for the application projects.
The first variant called µPyCraft offers a comparatively simple interface for MicroPython
development on the ESP32 controller. It works with simple graphic elements and resembles
text-oriented operating systems. The handling of the individual functions is easy to under-
stand and working with the different menus is easy to learn.
Thonny, on the other hand, has a fully graphical interface in Windows style. The IDE is very
popular among makers, especially because it is available under the Raspbian operating sys-
tem on the Raspberry Pi. Many Raspberry Pi users are therefore already very familiar with
Thonny.
The IDEs stand for the most important operating systems such as
• Windows PC
• Mac OS X
• Linux Ubuntu
If problems occur during installation or use of either system, the other version can be used
as an alternative programming system. The version to choose depends of course on the
personal inclinations and habits of the user.
1. Download the installation file from the Python download page at:
www.python.org/downloads
● 19
MicroPython for Microcontrollers
python-3.7.X.exe
3. Select "Add Python 3.7 to PATH" and click the "Install Now" button.
4. The installation process is completed after a few seconds and the message
"Setup was successful" is displayed. The window can then be closed.
https://github.com/DFRobot/uPyCraft
as a file called uPyCraft_V1.x.exe. After clicking on this .exe file, the uPyCraft-IDE will open:
After the IDE is installed on the computer, the ESP32 firmware can be loaded onto the chip.
The current version of the MicroPython firmware for the ESP32 can be found at
http://micropython.org/download#esp32
There you scroll to the section "ESP32 modules". After clicking the link to "Generic ESP32
module" you will get to the download page of the ESP32-BIN file. This will look as follows:
esp32-idf3-20191220-v1.12.bin
● 20
Chapter 3 • Programming and Development Environments
If the ESP32 board is connected to the computer but the ESP32 port does not appear in the
uPyCraft IDE, the appropriate USB driver may be missing. In this case, the driver must be
reinstalled. A corresponding driver can be found under
https://www.silabs.com/products/development-tools/software/usb-to-uart-
bridge-vcp-drivers
Now the MycroPython interpreter can be written onto the ESP32 using
● 21
MicroPython for Microcontrollers
• board: esp32
• burn_addr: 0x1000
• erase_flash: yes
• com: COMX (here COM5, see above)
Under "USERS", select the downloaded ESP32-BIN file, as shown in Figure 3.4.
If all settings are correctly selected, the "BOOT / FLASH" button on the ESP32 board must
be pressed on some board variants. As soon as the "EraseFlash" process begins, the key can
be released. After a few seconds, the firmware should have flashed onto the ESP32 board.
However, in many cases the download will start without pressing the buttons.
If the "EraseFlash" display does not start or an error message is displayed, repeat the steps
described above. Also press the "BOOT / FLASH" key again to ensure that ESP32 enters the
flash mode.
For this reason MicroPython does not contain the complete standard library, but only the
parts relevant for microcontrollers. Therefore, all modules required for accessing the used
hardware are available. With the corresponding libraries you can therefore easily access
the GPIO pins. Especially for the ESP32 there are also modules available to support network
connections (Wi-Fi) and Bluetooth. In particular, the following boards are supported:
• ESP32
• ESP8266
• PyBoard
• Teensy 3.X
• WiPy - Pycom
● 22
Chapter 3 • Programming and Development Environments
Although not all functions of the ESP controller are fully available in MicroPython as of yet,
the libraries contain the most important commands and routines. Therefore many projects
and applications can be implemented smoothly. In addition, the implementation of the miss-
ing features is progressing rapidly, so that even this small beauty flaw will be quickly elim-
inated.
Once the MicroPython firmware has been installed on the ESP32, you can also easily return
to the Arduino IDE, for example. To do this, simply load the new C code with the IDE onto
the controller. A special deletion procedure is not necessary. However, if you want to use
MicroPython again afterwards, the MicroPython firmware must be flashed again.
In the left sub-window ("Folders and files"), the files currently stored on the ESP board are
visible in the device folder ("device"). As soon as the board is connected to uPyCraft-IDE via a
serial connection, all saved files will be loaded when opening the device folder. Directly after
the installation of the Python interpreter only a "boot.py" file is visible here. To execute the
application code, a main.py file should also be created. You can create a main.py file using:
file → new
This creates a new file ("untitled"). Through the floppy disk icon in the "Tools" window this
file can be saved locally under the name "main.py" on the ESP chip.
● 23
MicroPython for Microcontrollers
The SD folder follows under the device folder. This folder is intended for accessing files stored
on an SD card. Some ESP-32 boards have an SD card slot. If a µSD card is inserted here, the
files on the card appear in the "sd" folder.
The uPy_lib folder follows below. Here the integrated IDE library files are shown. Here you
can find different files directly after the installation of the MicroPython interpreter. These are
provided as standard libraries.
The last folder contains the so-called "workSpace". This is a directory for saving application
files. The files displayed here are stored on the computer connected via the interface. All
active files should be stored there.
When uPycraft is used for the first time, it is therefore recommended that a suitable working
directory called "workSpace" be created and then used consistently for working with the
controller.
In the Editor area (2) the code for the .py application programs is created. The Editor opens
a new tab for each file.
● 24
Chapter 3 • Programming and Development Environments
The section below the Editor area is the "MicroPython Shell/Terminal" (3) All commands
entered here are immediately executed by the ESP board. In addition, the terminal also
displays information about the status of a running program. Any syntax errors in the current
program or error messages during uploading, etc., appear here.
With the symbols in the "Tools" area at the far right of the main window (4), tasks can be
executed quickly and directly. The buttons have the following functions:
In order to become familiar with writing a program and executing code on the ESP32, a
short Python program will be developed and executed below, which makes a LED flash. The
first step is to establish communication with the ESP board:
Now a print command can be entered to test whether the communication is working cor-
rectly:
The answer
Test
>>>
appears in the terminal window. When the message is displayed, everything is OK. Other-
wise, check that serial communication with the board is established and that the MicroPy-
thon firmware has been flashed successfully to the board.
● 25
MicroPython for Microcontrollers
Now a LED flashing script can be created. The following steps are required for this:
1. The following program is entered into the Editor window of the file main.py,
which was created above:
2. By clicking on the "Stop" button, a script that may still be running can be stopped
3. With a click on the button "Download And Run" the script is written to the con-
troller
4. The shell window should now show the message "download ok".
Now the integrated LED of the ESP32 board should flash every second. This means that
the first Python program was successfully transferred to the controller and executed im-
mediately.
● 26
Chapter 3 • Programming and Development Environments
Some boards do not have an integrated LED. In this case, an LED including series resistor
must be connected to the controller (see, for example, Figure 4.6 and Figure 4.7). Further
details and information on the flashing program and on connecting external LEDs can be
found in Section 4.4.
It is then even possible to transfer programmes to the controller via a terminal such as PUTTY
or TeraTerm. However, this method already requires some in-depth knowledge of the com-
mand line interface or the device manager. This procedure is therefore less recommended
for beginners. Nevertheless, the method will be described here, as it also provides further
insights into the handling of the controller programming. In addition, the methods presented
here can also be easily transferred to Linux or UNIX systems.
In order to work with esptool, Python 3.7.X or a newer Python installation should be installed
on the System System. The current version of esptool can then be downloaded to the com-
puter via a terminal window using
With some Python installations, this instruction may cause an error message to appear. In
this case, the following instructions may lead to the destination:
● 27
MicroPython for Microcontrollers
Now the esptool file should be installed in the standard directory for executable files. To
access the controller, its serial port number must be known. This can be found in the Device
Manager:
Figure 3.9: The COM port of the ESP32 in the Device Manager.
In the figure, the port number is COM3, for example. This allows the following command to
be executed in the terminal window:
This provides information about the ESP32 system connected to that port:
The lines
...
Detecting chip type... ESP32
Chip is ESP32-PICO-D4 (revision 1)
Features: WiFi, BT, Dual Core, Embedded Flash
● 28
Chapter 3 • Programming and Development Environments
Crystal is 40MHz
MAC: d8:a0:1d:40:54:14
...
Device: 4016
Detected flash size: 4MB
thus provide important information about the chip type, the board, the available interfaces,
the crystal frequency and the available flash memory.
This clears the way for uploading the MicroPython firmware. The download of the firmware
from the internet was already described in the last chapters. The command for the upload is
Of course, the correct path where the esp32-20xxxxxx- vx.x.x.bin file is located must again
be specified here. After a few seconds, the upload should be finished:
● 29
MicroPython for Microcontrollers
Now you can contact the ESP via PUTTY or TeraTerm. The baud rate must be set to 115200:
A first Python program can already be loaded via the terminal, for example:
● 30
Chapter 3 • Programming and Development Environments
After the program has been transmitted, an LED connected to port 23 should flash at a
1-second rate.
The console offers the usual help system, which can provide useful information if neces-
sary:
● 31
MicroPython for Microcontrollers
The examples in this book were created with Thonny 3.2. In principle, future versions
should be compatible with it. However, in case of unexpected problems, you should return
to the version mentioned above. The appropriate package can be downloaded from
https://thonny.org
When the download is complete, you can run the installation file. Now you only have to
follow the assistant until the installation process is finished. Afterwards the Thonny-IDE can
be opened.
Now the ESP32 board can be connected to the computer. To test the installation, Thonny
must be configured for the MicroPython interpreter. In addition, the board used must be
selected. The following steps are necessary for this:
● 32
Chapter 3 • Programming and Development Environments
Now the Thonny-IDE should be connected to the board and the shell window should show
the prompt ">>>". Alternatively the option "Try automatic recognition" can be selected.
However, this does not work reliably with all boards. Finally, the help() command is entered
into the shell. This will return a welcome message and some information:
import machine
pin12 = machine.Pin(12, machine.Pin.OUT)
pin12.value(1)
pin13 = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)
print(pin13.value())
i2c = machine.I2C(scl=machine.Pin(21), sda=machine.Pin(22))
i2c.scan()
i2c.writeto(addr, b'1234')
i2c.readfrom(addr, 4)
import network
● 33
MicroPython for Microcontrollers
Control commands:
CTRL-A -- on a blank line, enter raw REPL mode
CTRL-B -- on a blank line, enter normal REPL mode
CTRL-C -- interrupt a running program
CTRL-D -- on a blank line, do a soft reset of the board
CTRL-E -- on a blank line, enter paste mode
The installation and commissioning of Thonny has thus been successfully completed. The
hardware functions can now be activated via shell instructions. First of all the machine
module can be imported:
Alternatively, the standard LED available on most boards can be used. Via
• In the editor area, code is created and edited. Multiple files can be opened, with
a new tab available for each file.
• In the MicroPython shell, commands are entered that are to be executed imme-
diately by the ESP card. The terminal also provides information about the status
of an executed program, indicates errors related to uploading, syntax errors,
print messages, etc.
Other useful tabs are also available. These can be configured in the View menu. The "Var-
iables" tab in particular can often be used to great advantage. It shows all variables of a
program and their current values.
● 34
Chapter 3 • Programming and Development Environments
In order to become familiar with writing programs and executing code on the ESP32, the
already known script is used again, which makes the integrated LED of an ESP32 board or
an external LED blink.
1. When Thonny starts for the first time, the editor shows a file without title.
This file is saved as main.py. For this purpose, the file is saved via
file → save as
The code is available in the download package for this book and can be used initially via
copy and paste. Later it is explained how files can be copied directly from the PC to the
controller.
or by pressing function key F5, the code is transmitted to the controller. The following in-
formation is output to the shell:
When the ESP is restarted, first the boot.py and then the main.py is executed. If boot.py
is not present, it is started immediately with main. So the program should become active
immediately after uploading, and the LED on the selected port (No. 23 in the example
above) should blink.
● 35
MicroPython for Microcontrollers
With some board variants, it may also be necessary to press the ESP EN / RESET key.
The file can be opened as a new tab in the "This Computer" subwindow. It can then be
opened via the menu
file → save as
on which ESP can be saved under its name ("blink.py") The second selection "MicroPython
device" must be selected in the query (see figure).
The file is now uploaded to the board and appears in the sub-window "Files". From there it
can now be started with the green arrow key or F5.
Accordingly, it is also possible to download files from the chip to the computer by selecting
"This Computer". Other commands for deleting or renaming files etc. are also found in the
"file" menu.
• In many cases, restarting ESP with the integrated EN/RST key is already
successful.
• Within the Thonny-IDE, communication problems between PC and chip can often
be solved by pressing the "Stop / Restart Backend" button (or CTRL-F2).
● 36
Chapter 3 • Programming and Development Environments
or:
or:
In this case it is often helpful to interrupt the USB connection to the module and then re-es-
tablish it. You should also check whether the correct serial port is set under
This error could also indicate that the serial port is already being used by another program
such as a serial terminal or the Arduino IDE. If this is the case, make sure that all programs
that may be communicating serially with the ESP card are closed. Then the Thonny IDE
should be restarted.
After closing and re-opening the active window, you should be able to continue working
normally. If there are repeated crashes, the whole Thonny-IDE should be restarted.
Error 3: Thonny IDE no longer responds to the "Stop / Restart Backend" key.
After pressing the button "Stop / Restart Backend" you should wait a few seconds. The ESP
needs time to restart and restore serial communication with Thonny. If the "Stop" button
is clicked several times or very quickly one after the other, the ESP module does not have
enough time to restart properly. This may cause the Thonny IDE to crash.
Error 4: Problem when restarting the ESP card, running a new script or opening the serial
port.
● 37
MicroPython for Microcontrollers
is displayed, this may indicate a hardware problem. This is often caused by one of the fol-
lowing problems:
In these cases, the use of a high quality and shortest possible USB cable will help. Changing
to a different USB socket on the PC can also be helpful. For laptops, an active USB hub with
its own external power supply should be used. This way you are no longer dependent on
the performance of the laptop USB power supply.
If the problems persist or other strange error messages appear, it is recommended to up-
date the ESP board with the latest version of the MicroPython firmware. This will at least
prevent errors that have already been corrected from making work more difficult.
It may happen that the controller is too loaded to establish a USB connection. In this case,
clicking the button "Stop/ Restart Backend" several times may bring the desired success.
However, this repeated clicking should take place at certain intervals (see above).
When running a script that uses Wi-Fi, switches to sleep mode, or performs multiple tasks
in parallel, it is recommended that you try to establish communication three or four times.
If this is still not possible, the ESP should be flashed again with the current MicroPython
firmware.
● 38
Chapter 4 • First Steps in Programming
Python has been one of the most frequently used programming languages for several
years. One of the reasons for this is that it was very simply designed and is therefore easy
to learn. The development of MicroPython makes the programming of microcontroller sys-
tems comparatively simple and straightforward. This makes the programming language also
very suitable for beginners in the world of embedded systems.
The developers of MicroPython have set themselves the goal of making the programming
of digital electronics as easy as possible. In this way, the largest possible circle of users can
be addressed. Python programs can be found in the hobby area as well as in education
or scientific use. But professional developers too, increasingly work with Python. In the IT
industry, numerous market leaders such as Google or Amazon have been using Python for
their software developments for a long time.
In addition, freely available modules and libraries such as MatPlotLib, NumPy, SciKit or
SciPy provide extensive possibilities. These range from scientific data analysis to machine
learning and artificial intelligence.
MicroPython was developed as a slim version of Python 3. Since the language has to be in-
terpreted, it is generally slower than compiled systems. MicroPython was designed to work
as efficiently as possible on small embedded systems. Therefore it can also be run on micro-
controllers which are much slower clocked and have much less memory than typical personal
computers.
A disadvantage of classical Python programming is that low-level controls are very difficult to
implement. For this reason, the classic Python variants are used rather secondary in hard-
ware-related programming. This shortcoming is largely eliminated by MicroPython. Based on
the standard, the Micro version is also strongly based on Python 3 in its syntax. In addition
there are virtual machines and the associated libraries.
If one compares the two most popular programming languages in the microcontroller envi-
ronment, one finds that Python is more often preferred over C/C++. In the rankings of the
most popular programming languages, Python more and more often reaches the first place.
The competitor C/C++, on the other hand, is increasingly being relegated to lower ranks.
The reason for this development is mainly based on the following advantages of Python:
Beginners usually find solutions to their problems quickly in the forums. In other languages
this form of mutual support is not as pronounced.
● 39
MicroPython for Microcontrollers
In C, programming is done via control registers, pointers and other structures and instruc-
tions that are often difficult to understand. The firmware for the target controller must be
programmed, compiled and finally transferred to the controller with a programming device.
MicroPython integrates all these steps. With a simple mouse click, users can control low-lev-
el hardware such as LEDs, displays, or motors. The acquisition of analogue voltage values
or working with SD cards becomes child's play with the appropriate libraries. Integrated
memory cleaning and a dynamic allocation process enables efficient memory management
in Python. This means that you hardly need to resort to pointers or similar constructs, which
are usually difficult for beginners to penetrate.
The often-cryptic C-symbols like x++, <<, >> etc. as well as the complex variable declara-
tion represent a hurdle for the beginner which should not be underestimated. Python is known
for its simplicity and the excellent readability of the code.
Since MicroPython was developed as a "light version" for microcontroller applications, not
all libraries and functions of standard Python are supported. Nevertheless, you can easily
switch to the micro version if you are already familiar with Python. Only a few syntactical
structures or instructions are not available or applicable in MicroPython.
Python is interpreted. This means that the original program code is processed directly by the
target processor. Compilation is therefore not necessary. Python therefore offers the possi-
bility to execute a program once written on a wide variety of systems. For this purpose, only
a corresponding interpreter must be installed. One of the biggest advantages of Python code
is its comprehensive compatibility. Python programs can be executed on classic computers
under Windows, MacOS or Linux as well as on small single-board systems such as the Rasp-
berry Pi or comparable microsystems. Especially the use on the "RPi" (German: "Raspi") has
also contributed to the increasing popularity of Python.
With new powerful controllers such as ESP32, it has now even become possible to use Py-
thon efficiently and conveniently in this area as well. Firmly integrated constructs ensure
that programs can be easily developed on both a small and large scale. Python is therefore
excellently scalable. The possible encapsulation of data and program code in clear, usable
modules, i.e. objects, makes Python an object-oriented programming language. C++ is
generally used nowadays, especially in hardware-oriented programming. Classical Python
variants were not well suited for this purpose until now. With MicroPython this gap is now
closed.
C++ includes client applications as well as powerful server applications, device drivers and
embedded driver components. The area of application ranges from system software to ap-
plication programming. Since Python is a relatively new programming language compared
to C, it has not yet found universal use in all areas of information technology. However, it can
be seen that Python is gaining ground in practically all areas.
The main disadvantage of Python is certainly its comparatively low processing speed. Here
compiled languages like C can clearly show their advantages. Fast control loops or real-time
systems, vehicle controls and safety enquiries can be realised much easier and safer in C.
● 40
Chapter 4 • First Steps in Programming
Since these areas of application hardly play a role for non-professional users, though, the
speed disadvantage is hardly significant.
Python has also gained special importance in the highly topical field of artificial intelligence
(AI). Through extensive libraries such as NumPi, SciPi etc. and distributions such as Anacon-
da, Python has become the most popular programming language by far. All doors are there-
fore open for the experienced Python user. From hardware-related controller programming
to AI applications — with Python there are no limits to intuition and creativity.
In this chapter the basics of MicroPython will be compiled. You should have a functional
programming environment available, because the commands and instructions are always
illustrated with practical examples. These can then be immediately tested directly on the
target hardware, i.e. the ESP32. This does not remain a purely theoretical programming
course, but the knowledge acquired can be immediately put into practice.
It is not necessary to comment each program line individually. Experienced coders should
be able to understand individual instructions without comment. Only in the case of special
constructs or unusual or innovative lines of code is a single line comment recommended. For
subprograms or whole logical program sections on the other hand, a short explanation of how
they work should not be missing.
Simple comments will be introduced with the # sign. They begin with # and end with the
end of the line:
Multi-line comments can also be marked with a triple double-quate (") character ("""). The
same character string then ends the comment:
"""
first comment line
second comment line
"""
'''
This is a multi-line comment.
Prints "hello world".
'''
● 41
MicroPython for Microcontrollers
print("hello world")
Alternatively, the commentary function can be used in Thonny. It allows to mark several
lines as comments at the same time with the # (hash) sign.
The commentary function is also very suitable for commenting-out certain parts of the pro-
gram. If, for example, when testing a more extensive code, certain sections are not to be exe-
cuted on a trial basis, these can be marked with comment signs. The lines are then no longer
observed by the interpreter. This makes a time-consuming deletion and later reinsertion of
the program sections unnecessary.
● 42
Chapter 4 • First Steps in Programming
end = ""
hello world
The following two illustrations illustrate the print instruction versions again in the Thonny-
IDE:
● 43
MicroPython for Microcontrollers
if True:
# block 01
print ("True")
else:
# block 02
print ("False")
The number of spaces for indentations is variable, but the same block must always maintain
the same number of spaces for indentations.
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False") # The different indentation will lead to a runtime error.
● 44
Chapter 4 • First Steps in Programming
To test the instructions in practice, all you need to do is connect an LED with a series resistor
to the ESP32. The following figure shows the corresponding wiring diagram:
On the software side, a digital pin must first be initialized. For this purpose, a variable is
created which corresponds to the pin. This is not just a pin number, but a complete object
that knows all aspects of the pin. To use pins, the class "Pin" must be imported from the
module "machine".
● 45
MicroPython for Microcontrollers
The number 25 is the GPIO number. This is usually found as a printed circuit board number
near the corresponding pin. The instruction defines the pin as an output.
Figure 4.8: Pin numbers here (here 25 and 26) on the ESP board.
led.value(1)
This sets the I/O port to "1", i.e. it now carries a voltage of 3.3 V. If everything is connected
correctly, the LED on port 25 will light up after the command is executed via the console.
Resetting the pin to "0" (0 volts) will carry out the following instruction:
led.value(0)
Together with the sleep instruction (see also the following chapter) from the time module
you can now program a LED flasher (blink_simple.py):
# blink_simple.py
sleep(1)
the LED now flashes at one-second intervals, i.e. with a period of two seconds or a frequen-
cy of 0.5 hertz.
● 46
Chapter 4 • First Steps in Programming
Each I/O pin can also be used as a digital input. The corresponding initiation is carried out
via:
This allows the level applied to the pin to be detected, i.e. 0 for 0 V and 1 for 3.3 V. An open
input, i.e. a pin without any wiring does not provide a reliable result. Interference signals
such as 50 Hz interference, WLAN or radio frequencies can change the level randomly. To
prevent this, so-called pull-up or pull-down resistors are necessary. With the ESP32 these
can even be switched on internally. Using
carries a low signal on an open input. With the following program the functions can be tested:
# read_pin_25.py
while(True):
print(pin_in())
sleep(1)
● 47
MicroPython for Microcontrollers
In the hardware setup, a piece of wire can be used to test the circuit, which is connected
to GND or 3.3 V:
Depending on whether the wire bridge is connected to GND (0 V) or 3V3, the value 0 or 1
appears in the terminal. If the input is open, 0 (for pull-down) or 1 (for pull-up) is displayed
in the terminal.
The 1-kΩ resistor is used to protect the input. This reduces the chances of unintentionally
applied excessive voltages causing damage. Still, you should always avoid applying voltages
above 3.3 V to an ESP32 pin.
import time
time.sleep(seconds)
a fixed delay time in seconds can be set. Alternatively, only the sleep command itself can
be imported:
● 48
Chapter 4 • First Steps in Programming
sleep(seconds)
Although the command can also be used for fractions of a second, for very short delays it
is recommended to use
time.sleep_ms(milliseconds)
The disadvantage of these functions is that they work obstructively. This means that the
controller cannot carry out any other tasks during the waiting period because it is busy
counting processor cycles. An alternative is to use interrupts or other programming tech-
niques. Details are given in later chapters.
time.ticks_ms()
time.ticks_us()
They indicate the current system runtime in milli- or microseconds. A classic application is
the measurement of program runtimes. With the following code it can be shown, for exam-
ple, that mathematical operations require a certain amount of time:
# runtime.py
import time
import math
while(True):
start = time.ticks_us()
# x = math.exp(math.sin(22.5))
stop = time.ticks_us()
print(stop-start)
If the comment sign is removed before the calculation, the displayed processing speed
increases from approx. 100,050 µs to 100,170 µs. The calculation time for the formula is
therefore around 120 µs.
● 49
MicroPython for Microcontrollers
>>> a = 17
>>> print(a)
17
• The variable name should only contain numbers, letters and underscores.
• The first character of a variable name must be a letter or underscore.
• The variable name is case-sensitive.
Variables can be assigned values of different types. The types in MicroPython include num-
bers, strings, lists, dictionaries, tuples, etc. With type() the data type of variables and con-
stants can be checked, e.g.
>>> a = 17
>>> print(type(a))
<class ‚int'>
Numbers like 10, 100 or strings like "Hello World!" are constants. MicroPython offers the
keyword "const", which marks an unchangeable value:
a = const(33)
print(a)
• Integer (int);
• Floating point (float);
• Boolean (bool); and
• Complex.
● 50
Chapter 4 • First Steps in Programming
A number object is created as soon as a value is specified. With del() you can delete the
objects again. In the console it looks like this:
It is also possible to assign values to several variables at the same time, i.e. separated only
by commas, e.g.:
a, b = 1, 2
The result of the division (/) always returns a floating-point value, e.g:
12/3 = 4.0
1, 100, -8080, 0 , ……
Float corresponds to the real numbers. Scientific notation in exponentials can also be used:
>> a = 1.234e3
>>> a
> 1234.0
An important difference between integer and float is that integer values are stored exactly.
Float numbers on the other hand are rounded.
Variables of the type Bool can only take the two values "True" and "False". Here, too, a dis-
tinction is made between upper-case and lower-case letters.
The variable type "complex" is composed of a real and an imaginary part in the form of a
+ bj or complex(a, b). Both the real part a, and the imaginary value b can be floating point
numbers.
● 51
Random documents with unrelated
content Scribd suggests to you:
Hen. Nay, Henry, love. The name you gave me first.
By that alone I'll live upon your lips.
[Exeunt. Curtain]
Kent. So am I now.
La. Alb. Nay, you are one half woman, being married.
A wife's the key may ope her husband's heart
To all the world. She is the pick and pry
To every lock of trust, and weasels through
His secrets spite all seals. Swear, Hubert, swear
That Margaret shall not know!
La. Alb. O!
Kent. Come, I'll satisfy you, Eleanor.
Alb. A bruise?
Keep cover? Gods! And I stood still! The dog!
I'll after him and take him by the throat!
Alb. Enough!
He angered me!
La. Alb. Ah, sir, no need. I'm dead now with your words.
[Enter Henry, Kent, Lord Wynne. Lords and ladies, among whom is
Margaret, enter behind them]
[Exit Henry]
Kent. My God!
Hen. Then, Heaven, turn foul, thou dost not shine for me!
Rise, Hubert, rise, for I must love you still,
Though you have robbed me of the sun and stars.
[Exit Kent with Glaia. Margaret would follow, but is detained by lady
Albemarle, who is half swooning. Winchester kneels and kisses
the king's robe]
Win. My king,
Thou'rt still beloved.
Hen. O, speak!
Say anything!
Wynne. When you come with me, sir, that I may slit
The tongue that fouls my name!
[Exeunt Henry and lords. Lady Albemarle and Margaret are left alone]
Mar. Not?
I am his heart. His veins run not with health
Except as I know how they course, and beat
Concordantly. Doubt not he'll tell me all.
Mar. Eleanor?
La. Alb. Whence are those floods of fire? O, Hubert, save me!
Hen. [Quickly sealing it] Now it does not. Here splits my heart,
And half falls with thee, Hubert.
Alb. So I aim.
But if I'm blocked therein, I look to you
To keep me stationed in my feudal rights,
And what you venture for me I'll make good
With forty thousand men, or horse or foot.
[Curtain]
ACT II
Scene 1. A room in the earl of Kent's palace. An inner
room rear, cut off by curtains. Kent alone.
Kent. Now, Eleanor, wilt prove thee saint, or devil?
Wilt mend this breach, or must I perish in it?
Too well I know that soul's dark history
To think it may breed light. The moment globes
The years' full character; a whole life's face
Peeps out in smallest deeds. Yet wonders are.
And Eleanor may prove false to herself
To once keep faith with Heaven.
[Listens] Glaia? Ay!
[Goes to curtains rear, parts them softly, looks within and returns]
She did not call. I'll watch all night. 'Twill be
No added task since there's no sleep for me.
My Margaret is safe. They dare not touch
A princess of the blood. But I am down.
'Tis said and sung there is no greater pain
Than wrenches Fortune's nurslings when she flies.
Not so. False lady of the wheel, take all!
But O, to see my king yield to the wolves
Now fang-close to his heart—there is my death!
[Sits on a couch, his head bowed. Margaret enters, advances softly
and embraces him. He looks up, returning her caress]
Now let the world go on, I'll rest me here.
Why should I keep my hand proud on the helm,
War with the unsated surge, nor know the pause
That is the spirit's silent growing time?
Ah, Margaret, how little will content thee?
No more nor less than love and poorest me?
Kent. Margaret,
Thou hast my soul. Wilt keep it true for me?
Kent. Thyself?
Then trust my trust in thee, which meets thy love
As swallows meet the waking winds of Spring
And know where life is.
Kent. Margaret,
Go to the maiden lying yon and look
Once more upon her vestal face, then ask
If she know aught of guilt.
[Margaret looks silently toward the curtains]
ebookbell.com