Micropython

Using Rshell with MicroPython

Rshell Setup

While you may use a serial terminal program such as Tera Term or minicom to execute Python code with the REPL console, very soon you would like to write your Python code in a file (or a number of files) and upload them to an STM32 discovery or Nucleo board.

To make this process more convenient, you can try a tool call rshell. See its repository on github for details: dhylands/rshell: Remote Shell for MicroPython (github.com).

In summary, install it with:

sudo pip3 install rshell
sudo usermod -a -G dialout $USER

The last line allows you to run rshell without sudo.

Run rshell with this command:

rshell -p /dev/ttyACM0

The ‘-p /dev/ttyACM0’ argument specifies the serial port to which the STM32 board is connected. The one listed here is for Ubuntu hosts. It’ll be different if you are running on Windows or MacOS. If the connection is established, you’ll see the following:

Using buffer-size of 32
Connecting to /dev/ttyACM0 (buffer-size 32)...
Trying to connect to REPL  connected
Retrieving sysname ... pyboard
Testing if ubinascii.unhexlify exists ... Y
Retrieving root directories ... /flash/
Setting time ... Mar 10, 2022 21:28:02
Evaluating board_name ... pyboard
Retrieving time epoch ... Jan 01, 2000
Welcome to rshell. Use Control-D (or the exit command) to exit rshell.
/home/user> 

Rshell File Commands

Rshell commands are a lot like Linux shell commands. Most common ones include:

  • ls – List files
  • cd – Change directory
  • mkdir – Create directory
  • cp – Copy file
  • rm – Remove file
  • mv – Rename or move file
  • cat – To show the content of a file

The nice feature is the entire file system on the embedded board appears under the /flash directory. Therefore you may copy files to and from the embedded board using the cp command:

/home/user/> cp blink.py /flash/
Copying '/home/user/blink.py' to '/flash/blink.py' …
/home/user> ls /flash
blink.py   boot.py    main.py    README.txt pybcdc.inf
/home/user> 

REPL under Rshell

Another nice feature of rshell is that you may enter and exit the Micropython REPL environment all within rshell.

To enter REPL, type “repl”. To exit from it type Ctrl-X.

/home/user> repl
Entering REPL. Use Control-X to exit.

>>> import os
>>> os.listdir()
['boot.py', 'main.py', 'pybcdc.inf', 'README.txt', 'blink.py']
>>>
>>> exec(open('blink.py').read())
>>>
>>> (Ctrl-X to exit REPL)
/home/user>

The above example shows how we entered REPL, listed the files stored on the STM32 file system and executed the MicroPython program named blink.py (which blinked the LED 10 times). Finally we typed Ctrl-X to return back to rshell command prompt. We can show the content of blink.py with the cat command (in rshell):

/home/user> cat /flash/blink.py
import time
for i in range(1,11):
    pyb.LED(1).on()
    time.sleep(1)
    pyb.LED(1).off()
    time.sleep(1)
/home/user>