Projekte mit MicroPython und dem ESP8266/ESP32 - [Teil 1]

What is Micropython?

MicroPython was developed as a lean programming language for microcontroller platforms derived from Python 3.4, aka CPython. To allow systems with limited memory to work with the implementation, many of the features of CPython have been omitted, while other features that are useful and important for microcontrollers have been added.

Besides LUA and the Arduino IDE, which is based on the SDK2.2.1 from Espressif, MicroPython is a common programming environment for developing applications with microcontrollers. The firmware requires 256kB of flash memory and 16kB of RAM.

How to install MicroPython on a microcontroller and how to work with it is what I will introduce below, and I invite you to join me in this experiment.

In this post you'll learn:

  • which hardware you need for this item
  • which tool you need to transfer MicroPython to a microcontroller
  • where to get the software
  • how to use and operate it
  • how to get a first demo program running

Flashing MicroPython to a microcontroller

What hardware do you need? 

For this tutorial you need

an ESP8266 board, e.g.

Nodemcu Lua Lolin V3 Module ESP8266 ESP-12F or

Nodemcu Lua Amica Module V2 ESP8266 ESP-12F or

D1 Mini Nodemcu with ESP8266-12F or

or

an ESP32 board e.g.

ESP-32 DEV KIT C V4

ESP32 NODEMCU Module WLAN WIFI Development Board

All boards already have a USB-Serial (RS232) adapter on board. They are equipped with 4MB (4 MByte = 32 Mb = 32 Mbit flash memory (aka programme memory).

The boards are supplied with firmware and their own programmes via the USB interface and can exchange data with the PC. The firmware is the operating system for a microcontroller, without which the controller is neither addressable nor able to work. MicroPython is such an operating system. However, the boards mentioned are usually delivered with NodeMCU-LUA or AT firmware.

Those who want to work with MicroPython on it must first transfer the new firmware to the board. After the firmware, i.e. the operating system, has been uploaded, MicroPython programmes are then transferred in the same way,

The two groups of boards differ first of all in the microcontroller installed on them, the amount of programme memory and the number of connections led out, the pins. The more powerful ESP32 is the successor to the smaller ESP8266. Furthermore, there is a USB interface component on the boards. Which one it is can be seen from the product descriptions, which can be accessed through the links above. I will go into this again in a moment during the software procurement and installation.

Why did I decide to try the following board together with MicroPython? The ESP-32 Dev Kit C V4 has enough connection pins to connect all kinds of sensors. The second part of the post is about a measuring station, the values of which are to be retrievable via a browser or a mobile phone app. Because the ESP32 has various bus interfaces such as I2C, Onewire, SPI etc., each pin usually has more than one task and designation.


And why MicroPython? Well, because I've wanted to get to grips with this programming language for a long time. In the past, I had tried out some projects with LUA and the Arduino IDE and now I want to get to know something new.

But wait - a few things are still missing for the hardware equipment. To be able to connect the boards to the PC, I still need a USB cable with USB A to Micro-B plug for these modules. And for the first "conversation" with the ESP32 you still need a LED, red or green and a resistor of 330 Ohm. For a push button connection we need the push button and a resistor of 10kOhm. For the connections we have some jumper cables and a breadboard ready. 

So, in summary, this post uses:
Number Component Note
1 ESP-32 DEV KIT C4
1 USB cable USB-A to UBS-Micro-B
1 Red or green LED
1 Resistor 330 Ohm
1 Button
1 Resistor 10kohm
Jumper cable
Breadboard(s)


The software

All listed software parts are either subject to the GPL or comparable licence conditions and can be obtained free of charge from the Internet.

In order to be able to address the boards, the driver for the USB interface module is first required. Depending on the board, this may be a CH340G or a CP2102, as in my case with the ESP-32 Dev Kit C V4 board. The component is framed in red in the picture.


CH340G driver (no licence details) is needed for the Amica board for Windows and Mac, Linux does not need an extra driver:

https://github.com/nodemcu/nodemcu-devkit

CP2102 driver for Windows, Mac, Android, Linux does not require an extra driver:

https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers

µPyCraft

The tool for flashing the MicroPython firmware is µPyCraft (no licence details). The tool can be downloaded from GitHub. The package contains versions for Windows, Linux and Mac. In addition to the tools for flashing the firmware, µPyCraft offers an editor for MicroPython programs and a terminal for direct contact with the MicroPython command line interpreter (REPL).

Python 3.8.5

For µPyCraft to run at all, Python version 3.7 or higher must be installed on the PC. The current Python3 release is 3.8.5. Follow the link Latest Python 3 Release - Python 3.8.5 (GPL-compatible) to download. From the "Files" list at the bottom of the page, select the version that matches your Windows installation.

Firmware Binaries

Then comes the most important thing, the MicroPython firmware (MIT licence), without which nothing works. I get it from https://micropython.org/download/all/. The direct link for an ESP8266 is

https://micropython.org/resources/firmware/esp8266-1m-20200902-v1.13.bin

and I can get the firmware for the ESP32 here

https://micropython.org/resources/firmware/esp32-idf3-20200902-v1.13.bin

Please download all parts of the software and the corresponding firmware and place them in a directory of your choice. Once this is done, unpack and install the software.

Installing the software

Driver installation

The driver for the CP210x comes in the ZIP archive

CP210x_Universal_Windows_Driver.zip,

which you unpack into a directory of your choice. In the resulting folder, the file

CP210xVCPInstaller_x64.exe

started. If you are still using a 32-bit system, select the version for this.

In the welcome window, click on Next and finally on Finish.


Python 3.8.5

The installation file

python-3.8.5-amd64.exe

is started.


The box Add Python 3.8 to Path gets a tick, then I click Install Now.

To the question of whether changes may be made to the system, I answer with yes.


The setup runs through.


And finally the success message appears. The window is closed.

µPyCraft

The downloaded file is the ZIP archive.

uPyCraft-master.zip.

I unpack it into a folder of my choice.


A folder with the same name has been created. The software does not need to be installed any further and will be started later from the directory into which it has now been unpacked. You can also create a link to it on the desktop.

Now we can get started. Preparing the hardware takes only seconds and then we teach the ESP32 how to do Python.

Do you have all the software you need?

  • CP2102 driver
  • CPython
  • µPyCraft
  • MicroPython firmware binaries

Then we get the firmware onto the ESP32.

Flashing the firmware

I now connect the USB cable to a free USB socket on the PC and the USB micro B plug to the ESP-32 board. The red LED flashes briefly to indicate that the board is live.

The µPyCraft flash tool is started from the directory into which it was unpacked. From the series of Windows applications I choose the one with the highest revision number, i.e. uPyCraft_V1.0.exe.

After starting, a window appears for installing a character set, which I acknowledge with OK.


Three things are now necessary, then you can have a quick cup of coffee.

All actions run via the Tools menu.

The board, or the processor type, must be selected.


Then it's time for the serial interface. If the driver has been installed properly, you will now see at least one entry in the list of COM ports. In my case, COM1 is a real serial port, which many computers no longer have today; the CP2102 is therefore COM4.


When I call up the Tools menu for the third time, I select BurnFirmware. There are still a few settings to be made in this window.



The ESP32 is flashed from 0x1000, the start address for an ESP8266 is 0x0000. We select the firmware as the user and it is the downloaded file from MicroPython, so choose.


Click on ok to start the burning process.


That's it for the preparations. Now we'll try out whether everything really worked out.

Testing the new environment

After the flash process, the ESP32 must be restarted, press the EN button on the board next to the USB socket.


In the terminal window of µPyCraft a whole barrage of messages appears and at the end three greater-than signs are output ">>>". This is the command line prompt of MicroPython. This means that you can now send commands to the microcontroller at this point. Let's test this with the common command. I enter the following and finish with the Enter key:

 print("Hallo Welt")


MicroPython can also be used as a calculator.


Before we start creating programmes, I will briefly explain the most important functions and peculiarities of µPyCraft.


1 File window 

device
The files that are on the ESP32 are listed here. You can also move files from the working directory (see below) to here with the mouse. Right-click to open the context menu with further file commands.
sd This lists the files that are on the SD card if the ESP32 has a card slot and a card is inserted.
uPy_lib
Here you'll find the libraries integrated in µPyCraft.
workSpace
This is the working directory on the PC. The working directory is set with the first click after starting the programme for the first time. If you want to change it, click on initConfig in the Tools menu.


2 Editor window    

Here, programmes are edited that are newly created, loaded from the working directory or from the ESP32. 

3 Terminal window (REPL = Read-Eval-Print-Loop)

Here you can enter direct commands as on a Linux or DOS shell. In Windows, this is called a command prompt. We have already tried this out. 

Switch panel   

It provides the following commands.

A Create a new file window in the editor area
B Open a file from the working directory
C Save a file in the working directory
D Upload a file to the ESP32 and start it
E Stop a script running on the ESP32
F Cut or establish the connection to the ESP32
G Undo last editing operation
H Restore editing process
J Check programme for syntax
Delete terminal area.

Now that the handling of µPyCraft has become more transparent, we dare to operate additional hardware on the ESP32. Because the board only has one LED on the TX0 line (Pin1), I now add a LED and the necessary series resistor to the hardware, as shown in the illustration opposite. The LED is connected to pin GPIO2 via the resistor. The anode of the LED is connected to the resistor, which is the longer of the two legs. The cathode is connected to GND.


Python and MicroPython are extended in functionality by libraries, similar to LUA and Perl. If we want to use the GPIO pins, we have to include the class Pin from the library machine. This is done in the terminal window.

from machine import Pin

Because we want to make the LED flash later, we also need a delay. We import the class sleep from the library time.

 from time import sleep

The whole thing now looks like this.


We declare a pin object

led = Pin(2, Pin.OUT)        

The pin object led defines pin 2 as the output. The constant Pin.OUT also has "siblings": Pin.IN, Pin.OPEN_DRAIN and others with which you can define the exact behaviour of the pin. A complete list can be found in the MicroPython documentation.

Now I switch on pin 2 by assigning the value 1 or "True" to the property "value" of the object. The methods of the pin object can also be read about via the link. Methods are called by appending their name, separated by a dot, to the name of the object. The passing parameter follows in round brackets.

led.value(1)

To switch off, I assign the value 0 or "False".

led.value(False) 


As in LUA, Perl and C++, 0 is to be equated with False = false and everything that is not equal to 0 is to be equated with True = true.

Did you observe the LED when sending the last two commands? If you now constantly repeat both commands at intervals of 0.5 seconds each, you will have a flashing LED - no, that's not how it works at all. But that's how it works.

The commands we have used are entered in the editor window. When writing, make sure that the engaged lines are started with a tab and not with spaces. Python is programmed in such a way that instruction blocks are not recognised by curly braces or an "end" like C++, LUA, Perl and other programming languages, but by indentation and exclusion of the text.

from machine import Pin
from time import sleep
led = Pin(2, Pin.OUT)
i = 0
while i <=10:
led.value(not led.value())
sleep(0.5)
i += 1

 Switching the LED state is done by the line

led.value(not led.value()) 

which reads in the state at pin2, negates it and reassigns it to the output.

Send this script to the ESP32 using the upload button (D) and after a few seconds the LED will flash exactly 5 times and then remain switched on.


To conclude this post, I will introduce the connection of a push-button that starts the flashing sequence when it is briefly pressed.

We complete the circuit according to the following illustration.

 

from machine import Pin
from time import sleep
led = Pin(2, Pin.OUT)
button=Pin(5,Pin.IN)
while True:
    button = not button.value()
    if button:
        print (button)
        i = 0
        while i <=10:
            led.value(not led.value())
            sleep(0.5)
            i += 1

In addition to the LED pin, a second connector is declared for the push-button input.

button=Pin(5,Pin.IN)

To create an endless loop, like the loop circuit in the Arduino IDE, I add a while structure that encloses the rest. True as the expression for the condition ensures that the loop is run through until the programme is stopped by the stop button (E) or until a reset.

while True:

The pull-up resistor (10k) sets the GPIO5 input to 3.3V potential, which is identified in the programme as 1 or High or True. Zero, on the other hand, is taken as False. If the button places the input Pin5 at GND potential, the read command registers this as 0 or False. However, it is precisely in this state that the flashing sequence should start. Therefore, the state must be negated so that the following if enables the flashing sequence when the button is pressed.

if button:

The print command ensures that the logical state of the key is communicated in the terminal window.

print (button)

The rest is known.

The main purpose of this final programme is to show how structures are built in Python. Therefore, note the increasing indentation with each inserted structure. The default is 2 character positions, which the editor in µPyCraft provides by itself through the tab key.

Summary

Congrats, you did it.

  • You have learned what hardware and software is needed to tackle MicroPython projects.
  • You know how to install and use the different tools.
  • Lastly, you learned how to use the MicroPython environment and run a first Python programme on the module.
  • You can switch an output pin and query a digital input.
  • You know the meaning of indentation for creating programme structures.
  • With the help of µPyCraft you are able to talk to your ESP32 module.

The next part then deals with a more advanced project in which sensor values are to be recorded by the ESP module and transmitted to a terminal device via WiFi.

Would you like to do some homework?

  • Can you use MicroPython on your module to determine which numerical values are behind the constants Pin.IN, Pin.OUT and Pin. OPEN_DRAIN?
  • Why does the LED actually stay on at the end?
  • What possibilities are there to change the programme so that the LED is off at the end?
  • Can you get the programme to output the value of the pass counter i?
  • Change the last circuit and the programme so that negating the key information is not necessary.

Enjoy experimenting!

Here is the post for download as a pdf file

Interesting and further links

The MicroPython homepage

http://micropython.org/

The documentation of MicroPython

https://docs.micropython.org/en/latest/index.html  

MicroPython on GitHub

https://github.com/micropython

Esp-32Esp-8266Basics software

16 comments

Andreas Wolter

Andreas Wolter

@Stefan:
zu A: das Problem ist nicht so recht reproduzierbar. Zeitliche Verzögerungen sollten i.d.R. nicht auftreten. Tabtaste oder Leertaste → gegf. Auswahl + Enter; reagiert auf verschiedene Situationen unterschiedlich, je nach der Möglichkeit der eindeutigen Zuordnung von der Eingabe zum gewünschten Ergebnis.

zu B: Das Programm mit dem Namen boot.py auf den ESP schicken, dann startet es bei jedem Einschalten oder Reset. Das bringt aber während der Testphase nix, weil man eben an dem Programm basteln muss. Natürlich muss es dann danach erneut zum ESP geschickt werden.

Stefan

Stefan

Ich arbeite mit der Thonny IDE.
A) Die Codevollständigen funktioniert meist nur sehr träge… (wenn überhaupt) wie kann dies beschleunigt werden?
B) Wie kann das Python Programm auf den Controller gebracht werden, ohne dass man den ESP ständig mit dem PC Verbinden und von dort aus starten muss?

Rudolf Reiber

Rudolf Reiber

Die MacOS X Variante von »uPyCraft« ist nur schrecklich. Der Inhalt des Fensters ist so unscharf, dass einem schier schlecht wird. Es funktioniert zwar, aber der Anblick ist schrecklich. Dazu das Handling kein bisschen Mac-like.
Besser gleich mit Thonny einsteigen.

Jürgen Grzesina

Jürgen Grzesina

Herr Schliefer aus Südfrankreich sandte uns folgende Nachricht:

Bonjour Ich benötige Ihre Hilfe : Système : Window 10 Famille 2004 Installer le 18/10/2020 Version Système d’Exploitation : 19041.630 Module : AZ ESP32-WROOM-32 ESP8266 MOD-12F Reference : Was ist MicroPython? 1 Teil ===========Problem : Nach ausgeführter Installation kein Ergebniss bei « Test der neuen Umgebung » bei beiden Moduls. Remarque :EraseFlash und Burn OK Chargement ESP aber upyCraft kein ZIP Archive, uPyCraft_master.zip nicht gefunden ESP hat 2 Tasten neben der USB Buchse, aber keine mit EN, Welche drücken ? Es ww¨re net von Ihnen, wenn Sie mir helfen könnten die Flaschvorgänge einer Moduls zustande zu bekommen Herzlichen Dank mit freundlichen Grüssen Paul Schliefer
-—————————————————————————
Im nachfolgenden e-Mail-Verkehr konnte ich dann schrittweise die Problematik eingrenzen und zum Abschluss die Lösung präsentieren. Leider habe ich das im Blogbeitrag nicht nicht bereits geschrieben.

uPyCraft zwickt nach dem Flashen der Firmware die serielle Verbindung zum PC. Manchmal weist das Programm darauf mit einer Meldung hin aber eben nicht immer (warum auch immer?) Damit bekommt man auch keine Meldungen vom ESP mehr ins Terminalfenster, logischerweise auch dann nicht, wenn die Resettaste gedrückt wird. Stelle man über Tools – Serial die Verbindung manuell wieder her, dann klappt das auch mit der Konversation zum ESP32/8266. Ach ja, und die Taste für den Neustart ist bei manchen Boards mit EN und bei anderen mit RST beschriftet. Das kann auch zu Ratlosigkeit führen.

Paul SCHLIEFER

Paul SCHLIEFER

bonjour,
<Ich möchte mich bei Herrn Jürgen Grzesina für seine Hilfe herzlich bedanken, ohne Ihn wäre ich nicht über die Hürde gekommren. Es wäre nett wenn die seiten numeriert wären, bei Hilfe als Reference gut zu gebrauchen.
Ausserdem wäre es net wenn die zwei Endeckungen von Herr Grzesina zu finden wären
1. dass die En Buchse auch RST heissen kann.
2. dass man des Com-Port neu starten muss, wenn
die RST Taste kein Ergebniss gibt
Ich versuche weiter zu machen und hoffe auch weiterhin auf Herrn Grzesina erfolgreiche Unterstüzung
Mit freundlichen Grüssen aus Frankreich
Paul Schliefer

Ulrich Taaken

Ulrich Taaken

Hallo Zusammen,
danke für den Artikel.
Hier nach ein paar allgemeine Hinweise, da die Einstiegshürde doch sehr hoch ist.
Als Editor für alle Betriebssysteme ist VSCode + Pymakr Plugin sehr zu empfehlen.
Der Vorteil gegenüber C/C++ ist das direkte ausführen ohne kompilieren und upload, der Nachteil ist die Bibliotheksverwaltung mit teilweite unklaren Dokumentationen.

Jürgen

Jürgen

@ Hr. Drews
Schau doch bitte mal ans Ende der Seite. Oberhalb von
Interessante und weiterführende Links
findest du den Link zum PDF-Download

fritte

fritte

Hallo,
super Projekt und für meinen Kenntnisstand auch genau richtig. Die Anleitung startet vielversprechend mit allen Plattformen, um sich dann auf den Windows-Zweig zu beschränken. Leider funktioniert der angegebene Link zu english-sprachigen uPyCraft Dokumentation (bei mir) nicht. Er sollte besser https://dfrobot.gitbooks.io/upycraft/content/ heissen. Wenn mir weitere Dinge auffallen, hinterlasse ich weitere Kommentare.
Weiter so!

Lothar

Lothar

Toller Blog. Freue mich auf weitere Artikel microPython

Ulrich Klaas

Ulrich Klaas

Die ganze Toolchain für Linux gibt es nicht ??

Ulli

Jürgen

Jürgen

@ Thomas Bierschwale
Manche 8266-er Firmware sucht beim Booten bereits nach einem Accesspoint. Klappt die Verbindung nicht, weil es keinen AP gibt, oder dieser den ESP permanent abweist, dann spricht irgendwann der Watchdog an, weil ihn keiner streichelt oder füttert. Das führt zum wiederholten Neustart des Systems. Versuch mal eine andere Firmware zu flashen. Die muss natürlich für einen ESP8266 compiliert sein, ESP32-Versionen laufen auf einem 8266 nicht. Eine andere Möglichkeit ist eine zu schwache Energieversorgung. Du kannst es mal mit einem Elektrolytkondensator von 470µF – 1000µF parallel zur Versorgungsspannung versuchen. Ich tippe aber eher auf die erste Problematik. Das Blöde ist nur, dass die AP-Suche einkompiliert ist. Stünde der Code in der boot.py, dann könnte man den Start blocken und das Verhalten ändern.

Ich hoffe, ein bisschen weiter geholfen zu haben.

Thomas Bierschwale

Thomas Bierschwale

Super ARtikel und eine gute Gelegenheit sich mal mit einer neuen Programmiersprache auseinanderzusetzen. Leider habe ich Probleme mit dem ESP 8266, das ich mir mal für ein Sensate Projekt bei AZ gekauft habe. Nach Flashen und Reset läuft der Bildschirm immer durch und gibt irgendwie Mist aus. Es fängt an mit wdt reset
load 0×40100000, len 30712, room 16 … Sonderzeichen … MicroPython v1.13 etc.
>>>
Gibt man etwas ein, fff z.b. , gibt es richtigerweise einen Syntax Error und das Spiel wiederholt sich immer und immer wieder.
Kannst Du weiterhelfen?

Peter Scigalla

Peter Scigalla

Der Artikel macht Lust aufs Ausprobieren. Mir geht es nämlich wie Dr. Drews. Ich hatte mit älteren ESP-32 Dev Kits (V2) schon diverse Experimente unternommenen. Leider immer mit dem Ergebnis, dass beim erneuten Anschluss an den PC kein Python auf dem ESP erkannt wurde. Bei nächster Gelegenheit werde ich nun einen neuen Anlauf mit dem V4 wagen.
Danke für den Beitrag!
Peter

at-bh

at-bh

Sehr gute Beschreibung für den Einstieg. Jeder wichtige Schritt wird im Detail ausführlich erklärt, so kann ich die Python Schnittstelle endlich auch mal bei den ESP’s aktivieren. Bin schon sehr gespannt auf den nächsten Teil … Danke für den Beitrag

Thomas Kuesters

Thomas Kuesters

Ich vermisse die Einbeziehung von Thonny.
Die Oberfläche erleichtert m.E. die Programmierung deutlich.

Hr. Drews

Hr. Drews

Hallo Jürgen,
ein sehr interessanter Artikel. Habe auch schon das eine oder andere mit MicroPython ausprobiert, das war aber nicht immer so von Erfolg gekrönt. Nun würde ich das gerne in Ruhe nach diesem Beitrag ausprobieren. Würde mir dazu gerne den Artikel ausdrucken – das arbeitet sich einfach besser. Leider sind die Ausdrucke aus dem Browser heraus nicht so toll – viel zu große Bilder usw.
Normalerweise kopiere ich die Artikel dazu in Word und verkleinere die Bilder, reduziere die Zeilen-Abstände usw. Dieses Mal geht da aber nicht (Bilder kommen nicht mit rüber). Es wäre toll, wenn das wieder klappen könnte, oder der Artikel als optimierte PDF zur Verfügung gestellt werden kann.
Schönes Wochenende
L. Drews

Leave a comment

All comments are moderated before being published

Recommended blog posts

  1. Install ESP32 now from the board manager
  2. Lüftersteuerung Raspberry Pi
  3. Arduino IDE - Programmieren für Einsteiger - Teil 1
  4. ESP32 - das Multitalent
  5. OTA - Over the Air - ESP programming via WLAN