The easiest thing to do on a new board is to flash the built-in LED. This is the equivalent of the famous Hello World displayed on the terminal. This script will make the built-in LED blink every second. The idea 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’s best to know the basics of Python syntax before jumping into MicroPython.
First, ensure you have configured your IDE software for your Pico board. If necessary, you can refer to the following tutorial, the procedure to follow for configuring the Raspberry Pi Pico in Thonny IDE .
On Thonny IDE, it is better to save the code on the computer and not directly on the board. Thonny IDE will send the code directly to the MicroPython interpreter (via the REPL) when executing the script. To save the script on the board afterward, go to File → Save as.
Note that the Python script will not automatically launch when the Pico board is switched on . To remedy this, it is necessary to register the script on the board with the following name main.py . This is not very annoying during the development phase, but it is important to know when using a MicroPython script on a board.
The structure of a MicroPython script is as follows:
Each MicroPython script is preceded by a phase of importing the modules necessary for its proper functioning. This is equivalent to the
Arduino IDE 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: any element in Python is considered an object. For example, the input/output pins of the boards will be seen and manipulated as objects. MicroPython objects are easily used even without being an expert in object-oriented programming.
In the example script, we import from the machine module the sub-module
module contains most of the objects specific to MicroPython
. The module
is, in fact, a class that defines the operation of an input/output pin (GPIO). This is why we create a
, corresponding to the pin that controls the built-in LED. This pin is defined as an electrical output. The
object we created has functions to change its state:
turns on the LED, and
on turns off the LED.
The number of the pin connected to the integrated LED is 25 for the Raspberry Pi Pico and the uPesy RP2040 DevKit.
We add a one-second delay with the
function of the
module to see the blinking visually.
The code that makes the LED blink is contained in an infinite loop.
You will notice if you used to use Arduino code that there are no more
function: the script is executed once in a sequential way. So don’t forget the infinite loop to have a behavior similar to the Arduino sketch.