Discover MicroPython on ESP32 with your first script
One of the easiest things to do on a new board is to blink the built-in LED. This is like the famous Hello World text displayed in the terminal when learning a new programming language. Here is a script that blinks the built-in LED every second. The goal here is to show you an overview of programming in MicroPython.
from machine import Pin import time pin_led = Pin(25, mode=Pin.OUT) while True: pin_led.on() time.sleep(1) pin_led.off() time.sleep(1)
It is recommended that you know the basics of Python syntax before getting started with MicroPython.
First, make sure you have correctly configured your IDE software for your board.
On Thonny IDE, it is better to save the code on your computer and not directly on your board. Thonny IDE will send the code directly to the MicroPython interpreter (via the REPL) when running the script. To save the script on your ESP32 afterward, just go to File> Save as …
You will notice that the Python script does not automatically run when powering up the ESP32 . To fix this, you must save the script on the board with a specific name main.py . This is not usually a problem during prototyping, but it’s needed when the MicroPython script is permanently run on your ESP32.
The layout of a MicroPython script is as follows:
Each MicroPython script begins with importing the modules necessary to function correctly. This is equivalent to
in the Arduino code for external libraries:
The difference with MicroPython is that even basic objects must be imported . As a reminder, Python is an object-oriented language: all Python elements are considered as an object. For example, the ESP32 input/output pins will be seen and handled like objects. MicroPython objects can be used naturally without being an expert in object-oriented programming.
In the example script, we import the
submodule from the machine module. The
module includes most of the MicroPython specific objects. The
module is actually a class that defines the operation of an input/output pin (GPIO). We create a
object that corresponds to the integrated LED pin. This pin is defined as a digital output. The
object that we created has functions to modify its state:
we turn on the LED and
we turn off the LED.
The ESP32’s built-in LED is connected to pin number 2 (GPIO2)
To visually see the blinking, add a delay of one second with the
function of the
The code that generates the blinking is contained in an infinite loop to blink … endlessly.
If you used to use Arduino code, you would notice that there are no more the
functions: the script is only executed once. Therefore, we must not forget the infinite loop to have a behavior similar to the Arduino sketch. A code is available to have the same structure as in Arduino code with a
function and a