Getting Started with MicroPython on ESP32 – Hello World, GPIO, and WiFi

I’ve been playing with several ESP32 boards over the months, and tried several firmware images. I started with a tutorial for Arduino Core on ESP32, a few month later I tested ESP32 JavaScript programming with Espruino on ESPino32 board, and recently Espressif Systems sent me ESP32 PICO core development board powered by their ESP32-PICO-D4 SiP, and while I took some pretty photos, I had not used it so far.

So I decided to go with yet another firmware, and this time, I played with MicroPython on ESP32, and will report my experience with basic commands, controlling GPIOs, and WiFi in this getting started post.

Flashing Micropython Firmware to ESP32 Board

Source code is available on Github, as a fork of MicroPython repo as ESP32 support has not been upstreamed yet. We could built the firmware from source, but there’s also a pre-built binary which you can download on MicroPython website.

I’ll be using Ubuntu 16.04 for the instructions, which should be pretty similar for other Linux distributions, especially the ones based on Debian, and if you’re using Windows 10, you should be able to follow the same instructions after installing Windows Subsystem for Linux with Ubuntu on your computer.

Let’s open a terminal, to download the firmware (October 14):


If you have not done so already, install the latest version of esptool:


Now connect the board via a micro USB to USB cable to your computer. The log should like like:


In my case, the device is ttyUSB0, but it may vary depending on the board used. We can now erase the flash, and copy the firmware to the board:


If the last step is successfull,  the output should be similar to the one below:


As a side note, version 2.1 of esptool does not know about ESP32-PICO-D4, but it can still detect an ESP32 device, and the update went through normally.

Hello World Sample / Boot Log with MicroPython

We can test the firmware, by connecting to the board using minicom, screen, putty, or whatever software you feel most comfortable with. I went with minicom, setup a connection to /dev/ttyUSB0 device with 115200 bps baudrate. I immediately tested the print function, and made an hard reset to check out the boot log:


The reset command will first generate some errors message, before rebooting the board:


We can type help function to get some more help:


I also often refered to MicroPython 1.9.2 documentation to write this quick start guide.

The easiest way to test GPIOs is to connect an LED, since the board does not have any user LED, only the power LED. So I connected an LED to pin 21 via a transistor to ensure enough current passes through it.

Controlling the LED in the command line interface is easy. Import the machine library, set the pin to output, and change the pin level as needed:


Success! But what about doing a proper blink sample? MicroPython developers’ official PyBoard would show as a USB mass storage drive in you computer, where can copy Python files like boot.py and main.py files, but in the case of ESP32 PICO core, it appears the only option is to use the serial console for programming, as we can’t simply copy files to the board from the host computer.

I  found a solution on Techtutorialsx – which also has plenty of articles about MicroPython on ESP32/ESP8266. We need ampy script that can be install from our Linux terminal:


However, the first time I tried it I got an error:


I installed files module, but the error remained. So instead I installed it for Python 3:


I then created blink.py on my computer to blink the LED every 500 ms:


Before uploading the file to the board, you can try to run it as follow:


If you have plenty of errors here, that’s probably because your code is incorrect. Since I’m not very familiar with Python, it happened to me a couple of times, until I got the code right, and the LED was blinking as expected.

Now that we’ve made sure the code works, we can now copy our sample to the board…


… reconnect to the serial console, and verify the file is there:


To run the program type the following:


The LED should blink again. You can interrupt the program with Ctrl+C, and if you want to soft reset the board, press Ctrl+D.

In order to automatically start the blink program at each boot, rename blink.py to main.py, delete blink.py, and copy main.py instead:


Power cycle the board, and the LED should start blinking almost immediately.

ESP32 WiFi with MicroPython (Station and AP modes)

We’ve got GPIOs working, but one of the most important feature of ESP32 is obvisouly WiFi. I’ll start by configuring the board in station mode. First import the network library, set the board to station mode, and scan access points:


The latter should return a list of access points with ssid, bssid, channel, RSSI, authmode, and hidden status as explained here.


I can then connect the board to one of the access points with:


The log above with IP address should give  a clue, but you can check connection status with the following function:


and use ifconfig to get the IP info:


Switching to AP mode is easy with the three commands below configuring the board with ESP32-PICO-CNX SSID:


At this stage I can see ESP32-PICO-CNX on my phone, but it’s an open connection. We can change that with authmode option that can take 5 values:

  • 0 – open
  • 1 – WEP
  • 2 – WPA-PSK
  • 3 – WPA2-PSK
  • 4 – WPA/WPA2-PSK

I’ll use WPA2-PSK and define the password with the config function.


Working as planned…

ESP32 Web Server with Micropython

Many ESP32 project will require a web interface for monitoring or configuration. Let’s first setup the board as an access point using the command we’ve used above:


Now create webserver.py file based on Python code found here that’s supposed to return the status of some GPIO pins in an HTML table:


Copy the file to the board:


Start the serial console again, import/run the python sample we’ve copied, and connect to the board (in my case http://192.168.4.1):


 

It works as expected, but we wrote the HTML code inside the Python file, and you need to handle socket programming by yourself. To further simply the task, some MicroPython web servers such as MicroWebSrv, and Picoweb are available.

MicroWebSrv (Not working yet for me)

I tried to install MicroWebSrv first, but never managed to make it work. I still reproduce the step I followed in case somebody finds out what I did wrong. I got the code, and copied files from the Linux terminal:


We can check the files are where they are supposed to be:


Go into the terminal (aka REPL console) to start a basic example, after setting up a connection:


I could connect to the server, but I would always get 404 error.

PicoWeb

So instead I switched to picoweb, adapting the instructions here and there. It’s very easy to install.  First make sure you have a working Internet connection in your board (i.e. set station mode), and install the web server with upip:


That’s the output if everything goes according to plans:


Now let’s go back to the host computer to create an html document, for example index.html:


as well as picowebtest.py sample file that will request the HTML page from the board, and return it to the client.


You’ll need to change “192.168.0.108” by the IP address of your board.

Let’s copy both files to the board…


… go back to the serial console, connect in station mode, and run the sample:


Type or copy/paste the URL in the last line into a web browser, and you should get the output below.

ESP32 Bluetooth with MicroPython

There’s no Bluetooth support in the official MicroPython documentation, because it’s work in progress, and for the most adventurous MrSulry released an alpha version  a few days ago. The Bluetooth API is also in flux, but the basic code to enable Bluetooth should look like:


I’ll update that section once Bluetooth makes it to the stable release, and/or when I’m sure the API is frozen.

Other ESP32 (Micro)Python Resources

I’ve just covered a few things that can be done with MicroPyhon on ESP32, and beside the official documentation, you can also check the various MicroPython ESP32 tutoral on techtutorialsx blog. Loboris also made another MicroPython ESP32 firmware that supports pSRAM as MicroPython may use a lot of RAM. If you’re interested in Python for ESP32, but Zerynth is another option for Python on ESP32 that works with an IDE/GUI available for Windows, Linux and MAC OS X. [Update: Yet other options are Pumbaa a port of MicroPython running on top of Simba, and Pycom version of MicroPython]

Share this:
FacebookTwitterHacker NewsSlashdotRedditLinkedInPinterestFlipboardMeWeLineEmailShare

Support CNX Software! Donate via cryptocurrencies, become a Patron on Patreon, or purchase goods on Amazon or Aliexpress

ROCK Pi 4C Plus

20 Replies to “Getting Started with MicroPython on ESP32 – Hello World, GPIO, and WiFi”

  1. @Deets
    Thanks I’ve added them. I can see they are both fork of MicroPython.
    I understand that Pumbaa allows you to program Python right in the Arduino IDE or PlatformIO, and the Pycom version must have been made to add support for their own boards.

  2. This looks very promising and Python makes drafts, learning, overall time-to-market way easier and faster.
    However note that it will never have the performance of native C/ASM and you may soon need more RAM!

  3. @TC
    Python is very well known to be slow on PC. I don’t know how micropython performs though but yes let’s appreciate the simple and quick write time. What I’m curious about is the perf of lua for instance (speed and memory) and maybe rust compiled code.

  4. there is webREPL for micropython ESP8266 where one can do programming and upload/download sketch easily using web interface. but ESP32 micropython doesn’t have webREPL yet.

  5. @cnxsoft
    I see your WiFi AP connection reported a 58Mbps Link speed. (your 22 August article on PICO D4 stated just the presumably theoretical WiFi speed of 150Mbps) If I am not mistaken your previous ESP32 tests did not include a test of WiFi performance. Are you able to run a download throughput test in STA or AP mode ? Ideally the test should copy your usual sized test file from the WiFi input to some real-life sink, like a file on the USB connected PC, or failing that, to the PC using STA+AP Mode, which I assume will drop the DTR to around 50%, due to the single radio having to both receive and snd the data.

  6. TC :
    This looks very promising and Python makes drafts, learning, overall time-to-market way easier and faster.
    However note that it will never have the performance of native C/ASM and you may soon need more RAM!

    As yet I have had no opportunity to test, but I read somewhere (may have been the Donald Norris book on Micropython, Micropython on ESP runs quite efficiently with little speed reduction on ‘real-time’ apps.

  7. The reference sample app for Picoweb is Notes Pico, https://github.com/pfalcon/notes-pico . It’s a note-taking webapp which stores notes in a database in the filesystem. I never tested it on ESP32, but it runs on ESP8266 (which is pretty scarce on resources like RAM), so should run on ESP32 either (or on any other platform supported by MicroPython, which are many, though at the different stages of development, a full-stack app like Notes Pico requires a pretty complete port).

    What’s interesting is that Notes Pico wasn’t written for MicroPython from scratch, but was ported from a “desktop” Flash webapp written by some guy. The Flask original requires some tens of megabytes (or more) to run. The MicroPython version requires few tens on kilobytes (that’s what you have on ESP8266).

  8. @cnxsoft
    Something the Pycom version does that no others do: Verify SSL certificates. So if you’re aiming to develop a device around an ESP32 and want to avoid man in the middle SSL attacks, flash it with the Pycom firmware. It’s not immediately apparent how to do so, but I found instructions in their forum.

  9. @TC
    I found that I ran out of RAM quite quickly. There are ESP32-based devices such as Pycom’s W01 which have 4MB RAM (2MB usable by scripts) but they’re not breadboard-friendly.

  10. Sorry, but there are no “5V LEDs”. A LED requires a given current to lit up which is controlled by the in series resistor, and the value of the resistor obviously is smaller for a lower voltage.

  11. As per your guidance for soft access point of esp32 i have done programming in micopython. The Access point is created and it is visible in my android mobile. But when i connect my mobile to access point it is showing “saved” message instead of “connected”. If i follow same procedure using arduino code then i am able to connect my mobile with access point created by esp32. Any help is highly appreciable .

  12. @Shrikant
    This normally happens when the password is incorrect.
    Do you have any special character in your password? If so try with a simpler password first like abcdef.
    If it works, then try again with your more complex password, and escape the special character(s) as explained @ ttps://docs.python.org/2.0/ref/strings.html

  13. I want to communicate with an ESP32 from my mobile app. Ihave the following micropython code:
    import network
    ap = network.WLAN(network.AP_IF)
    ap.active(True)
    ap.config(essid=’ESP32′)
    ap.config(authmode=3, password=’123456789′)

    In this code the access point is created and it is visible in my Android mobile.
    But when connect my mobile to the access point it is showing the “saved” message instead of “connected” even though I have entered the correct password.
    I followed the same procedure using Arduino code and I was able to connect my mobile with the access point created bythe ESP32. Any help is highly appreciated

    @cnxsoft

  14. @Jeroen
    Hard to read ??? Compared to which language ? C or C++ maybe ? Are you kidding ?

    WRT to the slow reputation, this means absolutely nothing. Slow for doing what exactly ? BTW a “reputation” in a technical or scientific domain has strictly no value, since what matters is the assessment you could have done yourself for your precise context. Don’t let you be fooled by what self-appointed experts can say or write. Most of them knows only a little about the topic they are ranting about.

    Back to the point, of course Python runs slower than compiled C/C++. But don’t forget the 80/20 (or even 90/10 most often) rule. In case you don’t know what it means : 80% of the resources are used in 20% of your code. So just use the right tool/language at the right spot, re-coding critical parts (if any) in C and calling it from Python. Python has been designed from start to seamlessly allow this precisely. This is how some of its standard libs are coded, and same from scientific ones (NumPy, SciPy,…).

    I’m myself in the SW industry for nearly 40 years now and have a strong professional background in a plethora of languages, including C/C++, Fortran, Java, Ada, Pascal… and Python of course (to name just a few), plus a couple of assemblers too. I have developed in Python several embedded systems for sensor networks these last years, which are deployed in industrial contexts and on constrained targets, and which are running 24/7 for a while now. Ditto for quite complex Web applications, eating far less resources than their Java counterparts while offering similar performances. So my opinion is made, and it is based on real world situations. Writing the same stuff in C/C++ or Java would have taken ages for the same result.

    The bottom line is that Python really shines when used correctly and at the right place, and that this “slowness reputation” is a nonsense, resulting from a biased analysis originated by some opinionated or narrow minded guys and propagated by people not really questioning them.

    Maybe you should give it a second chance with a new perspective 😉

Leave a Reply

Your email address will not be published. Required fields are marked *

Khadas VIM4 SBC
Khadas VIM4 SBC