Using MicroPython and uploading libraries on Raspberry Pi Pico
Using rshell to upload custom code

MicroPython is an implementation of the Python 3 programming language, optimized to run microcontrollers. It's one of the options available for programming your Raspberry Pi Pico and a nice friendly way to get started with microcontrollers.

MicroPython can be installed easily on your Pico, by following the instructions on the Raspberry Pi website (click the Getting Started with MicroPython tab and follow the instructions).

After that point you might get a bit stuck. The Pico documentation covers connecting to the Pico from a Pi, so if you're wanting to code from your own computer you'll need something else. One option is the Thonny IDE which you use to write and upload code to your Pico. It's got a nice friendly interface for working with Python.

But if you don't want to change your IDE, or want a way to communicate with your Pico from the command line? You're in luck: there is a simple tool for accessing the MicroPython REPL on your Pico and uploading custom Python scripts or libraries you may wish to use: rshell

In this tutorial I'll take you through working with MicroPython in rshell, coding live and uploading custom scripts to your Pico.

Installing rshell

Rshell itself is built on Python (not MicroPython) and can be installed and run locally on your main machine. You can install it like any other Python library.

bash
python -m pip install rshell

Unfortunately, the current version of rshell does not always play nicely with the Raspberry Pico. If you have problems you can install a fixed version in the pico branch from the rshell repository. You can install this directly from Github with the following --

bash
python -m pip install https://github.com/dhylands/rshell/archive/pico.zip

This will download the latest version of the pico branch (as a .zip) and install this in your Python environment.

Once installed, you will have access to a new command line tool rshell.

The rshell interface

To use rshell from the command line, enter rshell at your command prompt. You will see a welcome message and the prompt will turn green, to indicate you're in rshell mode.

rshell on Windows 10 The rshell interface on Windows 10

rshell on macOS The rshell interface on macOS

If previous pip install worked but the rshell command doesn't work, then you may have a problem with your Python paths.

To see the commands available in rshell, enter help and press Enter.

python
help

Documented commands (type help <topic>):
========================================
args    cat  connect  date  edit  filesize  help  mkdir  rm     shell
boards  cd   cp       echo  exit  filetype  ls    repl   rsync

Use the exit command to exit rshell.

You can exit rshell at any time by entering exit or pressing Ctrl-C. Once exited the prompt will turn white.

The basic file operation commands are shown below.

  • cd <dirname> change directory
  • cp <from> <to> copy a file
  • ls list current directory
  • rm <filename> remove (delete) a file
  • filesize <filename> give the size of a file in bytes

If you type ls and press enter you will see a listing of your current folder on your host computer. The same goes for any of the other file operations, until we've connect a board and opened it's file storage -- so be careful! We'll look at how to connect to a MicroPython board and work with the files on it next.

Connecting to your Pico with rshell

Enter boards to see a list of MicroPython boards connected to your computer. If you don't have any connected boards, you'll see the message No boards connected.

If your board isn't connected plug your Pico in now. You can use the connect command to connect to the board, but for that you'll need to know which port it is on. Save yourself some effort and just restart rshell to connect automatically. To do this, type exit and press Enter (or press Ctrl-C) to exit and then restart rshell by entering rshell again at the prompt.

If a board is connected when you start rshell you will see something like the following...

python
C:\Users\Gebruiker>rshell
Connecting to COM4 (buffer-size 128)...
Trying to connect to REPL  connected

Or an equivalent on macOS...

python
Martins-Mac: ~ mfitzp$ rshell
Connecting to /dev/cu.usbmodem0000000000001 (buffer-size 128)
Trying to connect to REPL  connected

...which shows you've connected to the MicroPython REPL on the Raspberry Pi Pico. Once connected the boards command will return some information about the connected board, like the following.

python
pyboard @ COM4 connected Epoch: 1970 Dirs:

The name on the left is the type of board (Pico appears as pyboard) and connected port (here COM4). The label at the end Dirs: will list any files on the Pico -- currently none.

Starting a REPL

With the board connected, you can enter the Pico's REPL by entering the repl command. This will return something like the following

python
repl
Entering REPL. Use Control-X to exit.
>
MicroPython v1.14 on 2021-02-14; Raspberry Pi Pico with RP2040
Type "help()" for more information.
>>>
>>>

You are now writing Python on the Pico! Try entering print("Hello!") at the REPL prompt.

python
MicroPython v1.14 on 2021-02-14; Raspberry Pi Pico with RP2040
Type "help()" for more information.
>>>
>>> print("Hello!")
Hello!

As you can see, MicroPython works just like normal Python. If you enter help() and press Enter, you'll get some basic help information about MicroPython on the Pico. Helpfully, you also get a small reference to how the pins on the Pico are numbered and the different ways you have to control them.

python
Type "help()" for more information.
>>> help()
Welcome to MicroPython!

For online help please visit https://micropython.org/help/.

For access to the hardware use the 'machine' module.  RP2 specific commands
are in the 'rp2' module.

Quick overview of some objects:
  machine.Pin(pin) -- get a pin, eg machine.Pin(0)
  machine.Pin(pin, m, [p]) -- get a pin and configure it for IO mode m, pull mode p
    methods: init(..), value([v]), high(), low(), irq(handler)
  machine.ADC(pin) -- make an analog object from a pin
    methods: read_u16()
  machine.PWM(pin) -- make a PWM object from a pin
    methods: deinit(), freq([f]), duty_u16([d]), duty_ns([d])
  machine.I2C(id) -- create an I2C object (id=0,1)
    methods: readfrom(addr, buf, stop=True), writeto(addr, buf, stop=True)
             readfrom_mem(addr, memaddr, arg), writeto_mem(addr, memaddr, arg)
  machine.SPI(id, baudrate=1000000) -- create an SPI object (id=0,1)
    methods: read(nbytes, write=0x00), write(buf), write_readinto(wr_buf, rd_buf)
  machine.Timer(freq, callback) -- create a software timer object
    eg: machine.Timer(freq=1, callback=lambda t:print(t))

Pins are numbered 0-29, and 26-29 have ADC capabilities
Pin IO modes are: Pin.IN, Pin.OUT, Pin.ALT
Pin pull modes are: Pin.PULL_UP, Pin.PULL_DOWN

Useful control commands:
  CTRL-C -- interrupt a running program
  CTRL-D -- on a blank line, do a soft reset of the board
  CTRL-E -- on a blank line, enter paste mode

For further help on a specific object, type help(obj)
For a list of available modules, type help('modules')

You can run help() in the REPL any time you need a reminder.

While we're here, lets flash the LED on the Pico board.

Enter the following at the REPL prompt...

python
from machine import Pin
led = Pin(25, Pin.OUT)

led.toggle()

Every time you call led.toggle() the LED will toggle from ON to OFF or OFF to ON.

To exit the REPL at any time press Ctrl-X

Uploading a file

MicroPython comes with a lot of built-in support for simple devices and communication protocols -- enough to build some quite fun things just by hacking in the REPL. But there are also a lot of libraries available for working with more complex hardware. To use these, you need to be able to upload them to your Pico! Once you can upload files, you can also edit your own code locally on your own computer and upload it from there.

To keep things simple, lets create our own "library" that adjusts the brightness of the LED on the Pico board -- exciting I know. This library contains a single function ledon which accepts a single parameter brightness between 0 and 65535.

python
from machine import Pin, PWM

led = PWM(Pin(25))

def ledon(brightness=65535):
    led.duty_u16(brightness)

Don't worry if you don't understand it, we'll cover how this works later. The important bit now is getting this on your Pico.

Take the code above and save it in a file named picoled.py on your main computer, in the same folder you're executing rshell from. We'll upload this file to the Pico next.

Start rshell if you are not already in it -- look for the green prompt. Enter boards at the prompt to get a list of connected boards.

bash
pyboard @ COM4 connected Epoch: 1970 Dirs:

To see the directory contents of the pyboard device, you can enter:

bash
ls /pyboard

You should see nothing listed. The path /pyboard works like a virtual folder meaning you can copy files to this location to have the uploaded to your Pico. It is only available by a pyboard is connected. To upload a file, we copy it to this location. Enter the following at the prompt.

bash
cp picoled.py /pyboard/picoled.py

After you press Enter you'll see a message confirming the copy is taking place

python
C:\Users\Gebruiker> cp picoled.py /pyboard
Copying 'C:\Users\Gebruiker/picoled.py' to '/pyboard/picoled.py' ...

Once the copy is complete, run boards again at the prompt and you'll see the file listed after the Dirs: section, showing that it's on the board.

bash
C:\Users\Gebruiker> boards
pyboard @ COM4 connected Epoch: 1970 Dirs: /picoled.py /pyboard/picoled.py

You can also enter ls /pyboard to see the listing directly.

bash
C:\Users\Gebruiker> ls /pyboard
picoled.py

If you ever need to upload multiple files, just repeat the upload steps until everything is where it needs to be. You can always drop in and out of the REPL to make sure things work.

Using uploaded libraries

Now we've uploaded our library, we can use it from the REPL. To get to the MicroPython REPL enter the repl command in rshell as before. To use the library we uploaded, we can import it, just like any other Python library.

python
MicroPython v1.14 on 2021-02-14; Raspberry Pi Pico with RP2040
Type "help()" for more information.
>>>
>>> import picoled
>>> picoled.ledon(65535)
>>> picoled.ledon(30000)
>>> picoled.ledon(20000)
>>> picoled.ledon(10000)

Or to pulse the brightness of the LED...

python
>>> import picoled
>>> import time
>>> while True:
...     for a in range(0, 65536, 10000):
...         picoled.ledon(a)
...         time.sleep(0.1)

Auto-running Python

So far we've been uploading code and running it manually, but once you start building projects you'll want your code to run automatically.

When it starts, MicroPython runs two scripts by default: boot.py and main.py, in that order. By uploading your own script with the name main.py it will run automatically every time the Raspberry Pico starts.

Let's update our "library" to become an auto script that runs at startup. Save the following code to a script named main.py.

python
from machine import Pin, PWM
from time import sleep

led = PWM(Pin(25))

def ledon(brightness=65535):
    led.duty_u16(brightness)


while True:
    for a in range(0, 65536, 10000):
        ledon(a)
        sleep(0.1)

In rshell run the command to copy the file to main.py on the board.

bash
cp main.py /pyboard/main.py

Don't copy this file to boot.py -- the loop will block the REPL startup and you won't be able to connect to your Pico to delete it again! If you do this, use the Resetting Flash memory instructions to clear your Pico. You will need to re-install MicroPython afterwards.

Once the main.py file is uploaded, restart your Pico -- either unplug and re-plug it, or press Ctrl-D in the REPL -- and the LED will start pulsing automatically. The script will continue running until it finishes, or the Pico is reset. You can replace the main.py script at any time to change the behavior, or delete it with.

bash
rm /pyboard/main.py

What's next?

Now you can upload libraries to your Pico you can get experimenting with the many MicroPython libraries that are available.

If you're looking for some more things to do with MicroPython on your Pico, there are some MicroPython examples available from Raspberry Pi themselves, and also the MicroPython documentation for language/API references.

Continue reading

Building a MicroPython heart rate monitor  biology

Pulse sensors have become popular due to their use in health-monitors like the Fitbit. The sensors used are cheap, simple and pretty reliable at getting a reasonable indication of heart rate in daily use. They work by sensing the change in light absorption or reflection by blood as it pulses … More