Micropython for the ESP32 and Co. - Part 1: Installation and first programs Products Download Code Einting Login Password?Thank you for registration for your assessment!Thanks for your review!

Micropython for the ESP32 and Co. - Part 1: Installation and first programs Products Download Code Einting Login Password?Thank you for registration for your assessment!Thanks for your review!

By Dr. Günter Spanner (Germany) Python has experienced an enormous boom in recent years. Last but not least, various single-board systems such as the Raspberry Pi have contributed to its popularity. But Python has also become widespread in other areas such as artificial intelligence or machine learning. It is therefore obvious to also use Python or the MicroPython variant for use on microcontrollers. This article will deal with the basics of MicroPython, including the most important program commands and libraries. For a few small demo applications we will use an ESP32 controller, which we need to equip with firmware that interprets Python commands. We compile these commands using a development environment running on a PC. The Python commands can be sent individually or as a whole program from the PC to the controller - this works via USB, but also a WLAN network. But first things first!MicroPython for the ESP32 and Co. - Part 1: Installation and first programs Products Download Code Embed Login Forgot your password? Register Thank you for your rating! Thank you for Your rating!

Programming and development environments

In contrast to the Arduino system, several development environments (IDEs: Integrated Developing Environment) are available for working with MicroPython. The two most common programming environments are current

1. μPyCraft

2. Tony

In addition, the Anaconda Navigator, which is used primarily in the field of artificial intelligence, can also be used for programming controllers. Each method naturally has specific advantages and disadvantages. The μPyCraft IDE only offers a comparatively simple interface. It works with simple graphic elements and is reminiscent of text-oriented operating systems.Thonny, on the other hand, has a fully graphical Windows-style interface (Figure 1).

The IDE is very popular with makers, especially because it is available on the Raspberry Pi under the Raspbian operating system. Many Rasp Pi users are therefore already very familiar with Thonny. Thonny is available free of charge on the Internet for the most important operating systems such as Windows, Mac OS X or Linux Ubuntu.

In order to work with Thonny, Python 3 must be installed on the development computer. If this is not yet the case, the installation can be made later via the corresponding website. Thonny can then be installed yourself via [1]. For this purpose, the appropriate operating system is selected on the website at the top right. After starting the downloaded exe file, the usual installation process runs. The IDE is then available for the first Python applications.

Installation of the interpreter

Next, the current MicroPython firmware will be loaded. This can be found on the official MicroPython website [3]. A number of controller options are available here. This article will focus on the ESP32 in particular. Therefore, the latest (latest) version for this type of controller must be downloaded. To do this, click on the appropriate image with the caption Generic ESP32 module on the page under Espressif ESP-based boards. Several firmware versions are available on the page that now opens. It should be noted that the most recent version usually has the addition "unstable". This option is more suitable for developers of the interpreter firmware themselves or those who like to experiment. If you want to work with a stable system, you should use the first variant without choose the unstable addition, e.g.

GENERIC : esp32-idf3-20200902-v1.13.bin

Click on the appropriate link to download the firmware.

Now the controller board (e.g. an ESP32 Pico-Kit, see the Required Parts box) can be connected to the PC via USB.

The Thonny IDE is then started. The first step here is to call up the sub-item Select interpreter in the Run menu. The Thonny options window will then open (Illus. 2).

Several options can be called up on the Interpreter tab, including those for the ESP32. Then select the USB port on which the ESP32 is active under "Port". Alternatively, you can use the option < Try to detect port automatically > select. However, this does not work reliably in all cases.

The installer is now started under the Firmware entry. The port is not automatically adopted and must be entered again. Then select the firmware downloaded above. The installation process starts with Install. After closing the windows that are still open, nothing stands in the way of programming the ESP32 under MicroPython.


Working with Python means using libraries. Writing all programs from scratch would be highly inefficient at best. The outstanding success of Python is based to a large extent on the libraries available for it. Unfortunately, not all libraries can be used with the limited resources of a microcontroller. Therefore, a separate selection of libraries was developed for MicroPython. Many of these are already available as standard libraries when you download the Thonny IDE.

The two main standard libs in MicroPython are machine and time. The libs for the controller become available via the import statement. To make the library functions accessible, the following options are available, among others:

import modules

from module import name

In the first case, the complete module is included. In the second, only the routines that are needed. The machine module contains the functions related to the hardware of a specific controller. So, the functions in this module allow direct and full access to the control of hardware units such as CPU, timers, buses, I/O pins, etc. It should be noted that improper use of this module can lead to malfunctions, crashes and in extreme cases even Hardware damage can occur.

The Pin class is one of the most important functions in the machine module. A Pin object is used to control input/output pins. Pin objects are usually mapped to a physical pin on the controller. This means that output voltages can be controlled or input levels can be read.

The Pin class has methods for setting the pin mode, such as IN and OUT, which can be used to define a pin as an input or an output.

The time module provides various time-related functions. The sleep class from this module suspends execution of the current program for the specified number of seconds. The argument can also be a floating-point number to specify an exact sleep time to the nearest fraction of a second. The instructions

from machine import Pin

from time import sleep

provide the two functions pin and sleep. On the one hand, this allows the individual port pins of a controller to be addressed and, on the other hand, simple time control is possible. About the instruction

led = Pin(2, Pin.OUT)

an object led is created that is assigned to I/O pin #2 and defines it as the output pin. Various values ​​can now be assigned to this object. So the object is about


for example assigned the value 1. This means that the associated pin 2 now has high potential, i.e. 3.3 V in the case of the ESP32.

The REPL console

In order to make the status of a port visible, you can connect an LED with a series resistor there. Figure 3 also shows the connection of an OLED display, which is only used below.

The port and thus the LED can now be easily controlled via the so-called REPL console. REPL stands for "Read Evaluate Print Loop". The ESP32 can be accessed directly through this interactive MicroPython prompt. So using REPL is a very easy way to test statements or run commands. In the Thonny IDE, the REPL console is called "Shell" and is available in the lower right window. The instructions from the last section can be entered directly here (Figure 4).

After executing the last instruction, the LED should light up. The LED can be switched off again with led.value(0).

The REPL console has some interesting features that can be very useful when working with MicroPython. For example, previously entered lines of text are saved. Previously entered lines can be recalled using the up and down arrow keys. Another helpful feature is tab completion. Pressing the tab key will auto-complete the currently typed word. This can also be used to get information about functions and methods of a module or object. B. the addition to "machine", provided the machine module was previously imported as shown above. If you then enter the period (.) and press the tab key again, a complete list of all functions available in the machine module appears (Figure 5).

This makes it unnecessary to look up instructions, objects or methods in documentation in most cases.

WLAN access via WebREPL

One of the great things about the ESP32 is its excellent WiFi connectivity. So what could be more obvious than making the REPL console available wirelessly via WLAN. The WebREPL interface can be used for this. The first step to using WebREPL is to ensure that it is available and enabled on the ESP32. WebREPL is not enabled by default and must be enabled with a one-time command

import webrepl_setup

can be switched on via the serial interface. A prompt follows to enable or disable the feature and set a password. A reboot must then be carried out.

To use WebREPL on a WiFi network, the ESP32 must first be connected to the network. To do this, the following commands must be executed in the serial REPL:

import network

wlan = network.WLAN(network.STA_IF)


wlan.connect('ssid', 'password')

Of course, the correct access data for the existing WLAN must be used for the placeholders ssid and password. The instruction


then supplies the IP data with which the ESP was registered in the network (image 6).


import web repl


The WebREPL client is activated.Then the address can be displayed in a browser


are called. The IP determined via wlan.ifconfig() should be used for xxx.xxx.xxx.xxx. You can then log in via the Connect tab with the password specified above in the WebREPL setup. After starting WebREPL, the console may be in "raw REPL" mode. This is used for direct input of command lines via "copy and paste". It may be necessary to switch back to normal mode with CTRL-B. Then the instructions can be entered as usual. In this way you are now able to control the ESP completely wirelessly. Even basic home automation functions can be implemented using simple switching functions (Figure 7).

If a suitable file system is installed on the ESP32, even software updates can be made wirelessly, i.e. OTA (Over The Air). When working with WebREPL, it should be noted that this is still an "experimental feature" that does not yet work absolutely reliably in all situations.

Program control

The REPL or WebREPL console is ideal for testing purposes. The editor window above is available for classic program sequences. There, for example, the following program for an automatic run-on control (night light, staircase lighting) can be created (Figure 8).

After entering and starting the program with the start icon (white arrow in a green circle), you will be prompted to save the program. Here the option MicroPython device is selected and a program name (e.g. Automatic_LED) is entered and the program is saved. The LED then lights up for 3 seconds and then goes out automatically. The program can now be started directly by pressing the start button again.

In order to implement the classic demo program (a flashing LED), only the while statement is missing. This ensures that a command or a block of commands is executed repeatedly. The special case while True: leads to an endless repetition, i.e. a permanent flashing of the LED:

from machine import Pin

from time import sleep

led = Pin(2, Pin.OUT)

while True:





Note that the while statement must end with a colon. According to the general Python convention, the following function block is to be marked by indentation over spaces. However, Thonny has automatic indentation. As soon as the return key is pressed after the colon, the cursor already appears in an indented position in the next line. Of course, TAB completion is also available in the program editor. Running programs can be terminated with CTRL-C.

MicroPython in a Nutshell

Although MicroPython thrives on its libraries, some understanding of the elementary statements is required to understand or develop programs. In the following, the most important MicroPython instructions are presented in brief. Simple comments are introduced with the # character. They start with # and end with the newline:

>>> print("hello ESP32") # this is a comment

hello ESP32

A comment is ignored in the program flow because it is only intended to provide information for the program developer. Information can be output to the terminal using the print() statement, which is also used here. print() can be executed directly in the terminal window, and the statement is used in programs to output text-based information. As already became clear with the LED flashing program, in MicroPython different blocks are denoted by indentation. This means that curly brackets ("{}") or similar are no longer necessary. The advantage of this method is that you are, so to speak, forced into structured programming to a certain extent. Variables are particularly easy to create in Python. It is not necessary to specify a data type. Variables can also be used directly in the console:MicroPython for the ESP32 and Co. - Part 1: Installation and first programs Products Download Code Embed Login Forgot your password? Register Thank you for your rating! Thank you for Your rating!

>>> a=17

>>> b=12

>>> print(a*b)


In MicroPython, arithmetic operators have the meanings known from mathematics. In addition to addition, subtraction, multiplication and division, the operators // for integer division % for modulo (i.e. remainder of division) and ** for exponents are available.

In addition, the usual branching and looping statements are available in MicroPython. In a branch, a condition is defined in the program using the keywords if and else. Depending on whether this condition is true or false, the program continues at different points. The else statements are only executed if the if statement is false:

if True:

# block 01



# block 02


Loops are used to repeat statements. Execution continues until a specified condition is met. Two variants are available:

• 'while' loops

• 'for' loops

If, for example, the numbers 1 to 9 are to be output to the console, the following while loop can be used:


while number<10:



The code to be repeated is indicated by the indentation. The task can also be done with a for loop:

for number in range(1, 10):


Automatic distress signals

With the now known program structures, a first practical application can already be implemented. The program creates an automatic SOS beacon that can be used in distress at sea or in the mountains:

from machine import Pin

from time import sleep


while True:

for n in range(3):






for n in range(3):






for n in range(3):






The OLED display: A small screen

Even with a single LED, meaningful information can be output if, for example, Morse code is used, as in the SOS beacon. Of course, the data output via an OLED display is much more up-to-date. A common type are displays controlled by an SSD1306 display controller. We use a display unit that has a resolution of 128 x 64 pixels at a size of only 0.96 inches (approx. 2.5 cm). MicroPython already includes the library for SSD1306 displays as standard. This enables text and numerical data to be displayed as well as simple graphics. The simplest versions of the SSD1306 modules only have four pins. This is sufficient to activate the display via the so-called I


Control the C-Bus. The connection of the display is already shown in figure 3. The required connections are summarized again in tabular form below:

The script in Listing 1 prints a text message and a simple graphic element in the form of a frame on the display (see Figure 3).

The associated library is available as a standard library (ssd1306.py in the download below) and can be uploaded separately to the board. The pin declaration for the I


C-Bus takes place via:

i2c = I2C (-1, scl = pin (22), sda = pin (21))

The "-1" parameter indicates that the module used has neither reset nor interrupt pins. The number of pixels of the connected module is

oled = SSD1306_I2C(128, 64, i2c)

captured. The display is now ready for operation. Information is output to the display via the text() function. The display is updated with the show() method. The text() function accepts the following arguments:

• message (type string)

• X position and Y position of the text box in pixel units

• Optional text color: 0 = black (dark) and 1 = white (light)

The show() method makes the changes visible on the display. For example, the rect() method allows the graphical representation of a rectangle. It accepts the following arguments:

• X/Y coordinate of the lower left corner of the rectangle

• Y/Y coordinate of the top right corner of the rectangle

• Pixel color: 0 = black, 1 = white

The instruction

oled.rect(5, 5, 116, 52, 1)


conjures up a rectangular frame on the display. This means that nothing stands in the way of using the display to output information, from simple text to the display of complex sensor data.

Summary and outlook

With MicroPython, a modern and powerful programming language is available. More complex projects can also be implemented quickly and easily using libraries. After the installation of the associated IDE and some simple application examples were presented in this first article, further aspects of MicroPython are explained in a second article. A large-format LED dot matrix display will then be presented as a practical application.

More information about MicroPython, the ESP32 controller and the examples presented here can be found in the book "MicroPython for microcontrollers".

More about MicroPython

Want to learn more about topics like ESP32 and MicroPython? Subscribe to Elektor and never miss an article, DIY project or tech tutorial.