RP2040 MicroPython: Getting Started

8 minute read

Where I demonstrate how to begin to program the RP2040 (Pi Pico and Pi Pico W) using Micropython.

Introduction

I already have quite a few entries on Micropython. While I’ve experimented with multiple boards using the language, ESP32, FIDI, and the Adafruit Feather RP2040, this entry begins a set of entries on using Micropython as a development language with the Pi Pico W as the development microcontroller. The cost ($6) of the Pico W along with it’s computing power, and wireless capability coupled with the ease of development of Micropython, makes this combination compelling.

1. Documentation

Books

I highly recommend having documentation to help you on this journey. These two books are free and are extremely valuable.

Action: Download them and have them available on your computer.

In addition to the books above, the following links will be important.

Action: Bookmark these links them and have them available in your browser.

2. Tool Chain

Install the following tools, as all of my examples will use them.

Action: Install all items from steps 1-3 appropriate to your computer’s operating system.

2.1. Multi-platform, install the appropriate version

2.2. Windows-specific:

2.2. macOS-specific

  • For command line interface (CLI), use Apple’s Terminal program
  • Python 3 for macOS - Use the homebrew installer for macOS

2.3. Install, once Python is installed

  • mpremote - Use pip to install mpremote once Python is installed. See below for more detail.

3. MicroPython Installation

Action, perform the following two steps:

3.1. Install a RESET button

For ease of use, I recommend the following steps:

  1. Install header pins or purchase your Pico W with header pins.
  2. Plug your board into a breadboard.
  3. Create GND rails [See Note:] on your breadboard by connecting wires (gray wires in image) from a GND pin on the Pico to the blue “-” rail on the breadboard. (I use pin 3 on one side and pin 38, on the other side).
  4. Plug a push button spanning the center channel into your bread board at the end of the Pico
  5. Connect a wire (gray wire in image) into one end of the push button to GND
  6. Connect a wire (blue wire in image) into the breadboard row diagonally opposite the GND connection to pin 30 RUN on the Pico.
    Pico W with Reset button

    Pico W with Reset button

Large Version to see detail

Note: The value of creating GND rails, is that it makes it easy to ground other components as you extend the functionality of your Pico with hardware. The blinkenleds are a good example below.

3.2 Install MicroPython

Download

To use MicroPython on the Pico, you must download the UF2 file which contains MicroPython for the Pico W. It can be found under Firmware, on the link above (…Pico W download). If you want the code discussed in this entry, you may download it here.

USB Mode

Having a reset button enables you to easily put the PICO W into USB mode. With a USB cable plugged between your PICO and your computer:

  1. Press and hold the BOOTSEL button on the Pico W.
  2. Press and release your reset button
  3. Release BOOTSEL.

Your board will show up on your computer as a USB drive labeled RPI-RP2. If the board doesn’t show up, check your connections to the Reset button.

  • Is there a wire from GND on the Pico to the GND rail on the breadboard?
  • Is there a wire from the GND rail on the breadboard to the button?
  • Is there a wire from pin 30 RUN to the button?
  • Are the connections to the button diagonally opposite? (as compared to straight across)
  • Did you follow the 3-step sequence above exactly? The timing is critical.

Drag and Drop

Now drag the .uf2 file you downloaded from the MicroPython site and drop it on the USB drive RPI-RP2. It will take several seconds to copy the 1MB+ size file on to the Pico and the board will restart, automatically ejecting itself from the computer. (For which the computer might complain, however, its not a big deal.)

3. Test Using Read-Evaluate-Print-Loop (REPL)

Serial Monitor

A nice advantage of Python is to be able to test out snippets of code using Read-Evaluate-Print-Loop (REPL). To use this mode, connect to the Pico using a serial monitor such as CoolTerm. Press Ctrl-C and you will be greeted by the REPL prompt.

If CoolTerm is an issue on your Mac, I also recommend tio as a great multi-platform serial program. It works well, doesn’t have issues when you press reset, and when you press Ctrl-C, it responds correctly and enters the REPL. You won’t be able to easily to disconnect and reconnect, as you can with CoolTerm.

To use tio, you will need a command line application (CLI), commonly called a terminal window. In macOS, its called Terminal. Start Terminal then use brew install tio, to install in macOS. To run tio, tio -b 115200 /dev/cu.usbmodem31401, your port may be a different number.

As an example using CoolTerm, while running my microserver application, I entered the REPL using Ctrl-C:

Starting sync server on 0.0.0.0:5001...
Traceback (most recent call last):
  File "main.py", line 101, in <module>
  File "main.py", line 97, in web_server
  File "microdot.py", line 1099, in run
KeyboardInterrupt: 
MicroPython v1.20.0 on 2023-04-26; Raspberry Pi Pico W with RP2040
Type "help()" for more information.
>>> 

The line KeyboardInterrupt indicates I hit Ctrl-C, the traceback is where it was executing in my program and the >>> indicates we are now in REPL mode.

Test example

Practice by typing the lines highlighted. Lines 5-7, simply need to be carriage returns then the loop will start. Don’t type the “>>>” or the “” as those are the prompts for the REPL.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> print("Hello, World!")
Hello, World!
>>> for i in range(5):
...     print(f"Printed {i+1} time(s)")
...
...
...
Printed 1 time(s)
Printed 2 time(s)
Printed 3 time(s)
Printed 4 time(s)
Printed 5 time(s)
>>>

Anytime where you are confused as to how to use a command or section of code, it is a good practice to test it using the REPL. You can type it in or use paste mode (below) to enter the code into the REPL.

Edit and Paste Mode

Editors

As recommended above, I will use the cross-platform programmer’s editor, called Sublime Text. I highly recommend it and particularly recommend it, if your are wanting to learn how to program for the long-term. In the next entry, I will show how to automate Sublime Text to enable you to be very efficient.

Other programming editors which would work well are Notepad++ on Windows, BBEdit on macOS or Kate on Linux. I don’t recommend beginning programming using Microsoft’s VS Studio or VS Studio Code. These are Integrated Development Environments (IDE), and their complexity will reduce your efficiency and ability to learn the Python language quickly.

Using Paste Mode

For simple programs, use paste mode.

  1. To enter paste mode, press Ctrl-E while in the REPL
  2. Select and copy all of the text you wish to copy in your code editor
  3. Paste it in the REPL window in the serial monitor.
  4. Press Ctrl-D to exit paste mode

It will look something like this, using the blink program below in Example Programs:

paste mode; Ctrl-C to cancel, Ctrl-D to finish
=== from machine import Pin
=== import time
===
===
=== def Blink():
===     led = Pin("LED", Pin.OUT)
===
===     while True:
===         led.toggle()
===         time.sleep_ms(250)
===
===
=== if __name__ == '__main__':
===     Blink()
===

Once you hit Ctrl-D to complete the transfer, the program will begin to execute. In this situation, the Pico W LED began to blink.

Example Programs

Classic blinking program. This version of blink is slightly more complicated than the typical blink. It allows you to use the program via an import method, which is valuable in debugging. It is my standard form of blink.

from machine import Pin
import time


def Blink():
    led = Pin("LED", Pin.OUT)

    while True:
        led.toggle()
        time.sleep_ms(250)


if __name__ == '__main__':
    Blink()

hello

I was having issues having a prompt show up at the beginning of a program, the program seemed to be skipping my initialization code. After other tests, I realized it might be how I was calling print, so I wrote a program which would simply loop printing “hello world” with a delay. It seemed to work fine…until I realized I wasn’t sure when the first “hello world” was printing. I added a counter to determine, when the first print would appear:

import time

i = 0
while i < 200:
    print(i, "Hello World!")
    time.sleep_ms(10)
    i += 1
When I did that, my results were:

[Connected]
2 Hello World!
3 Hello World!
4 Hello World!
5 Hello World!
6 Hello World!

Oh, my. I was able to see the “Hello World!” only after the third time through the loop! I need to delay my print statements for about 2 seconds for the serial port to connect.

After a series of tests using the program stored on the Pico, I tested tio, mpremote and my macOS serial application called Serial. Its clear that the fault lies with the program, Serial. Both tio and mpremote will show the first two lines of text accurately. Good to know!

I included this program as part of the copy/paste examples, as it is a good test of the serial interface. The program will show the index of a 10ms delay. If the index starts at 0, there is no delay. Otherwise the delay is value of index * 10ms.

Once you feel comfortable with paste mode, go to RP2040 MicroPython: Developing Applications to begin more advanced program creation.

Comments powered by Talkyard.