Skip to main content

Working with MicroPython

This chapter contains the following sections. Please read as needed:

MicroPython Getting Started Tutorial

New to Pico MicroPython development and want to get started quickly? We have prepared a general introductory tutorial for you. These tutorial is designed to help developers quickly become familiar with Thonny IDE and start developing. It covers environment setup, project creation, component usage, and peripheral programming, helping you take the first step in MicroPython programming.

Setting Up the Development Environment

Please refer to the Install and Configure Thonny IDE Tutorial to download and install the Thonny IDE.

Example

The MicroPython examples are located in the examples\MicroPython directory of the example package.

ExampleBasic Program DescriptionDependency Library
01_SDMount TF card-
02_RTCGet RTC data-
03_GUIGUI display program-
04_KEYButton test-
05_SHTC3Temperature and humidity sensor test-
06_TOUCHTouch screen test-

01_SD

Example Description

  • Uses SPI to communicate with the TF card and mounts the TF card to the development board. After successful mounting, you can view and modify the contents of the TF card via Thonny.

Hardware Connection

  • Insert a TF card
  • Connect the board to the computer using a USB cable

Code Analysis

  • sdcard.SDCard(spi, cs, baudrate): Creates a TF card object and binds the initialized SPI interface and CS pin to the TF card driver.
  • uos.mount(sd, '/sd'): Mounts the TF card file system to the /sd directory. After successful mounting, users can perform file read/write operations on the TF card via the /sd path, such as creating, reading, or deleting files.

Operation Result

  • Upload all py files from the 01_SD folder to the development board via Thonny and reset the board. After resetting, the development board will automatically mount the TF card to the sd directory according to the boot.py program.

    MicroPython-Example-2

02_RTC

Example Description

  • Uses I2C to communicate with the onboard RTC chip, sets and reads RTC time data, and tests if the RTC interrupt is functioning correctly.

Hardware Connection

  • Connect the board to the computer using a USB cable

Code Analysis

  • RTC = PCF85063(): Creates an RTC object.
  • RTC.setDate(weekday, day, month, year): Sets the RTC date.
  • RTC.setTime(hour, minute, second): Sets the RTC time.
  • RTC.readTime(): Reads the RTC time.
  • RTC.setAlarm(second, minute, hour, day, weekday): Sets the RTC alarm.
  • RTC.enableAlarm(): Enables the RTC alarm.

Operation Result

  • Run the py files in the 02_RTC folder using Thonny.

    MicroPython-Example-2

03_GUI

Example Description

  • Drives the display via SPI communication, uses GUI drawing functions to draw text, borders, and color blocks, and refreshes the screen to complete the display.

Hardware Connection

  • Connect the board to the computer using a USB cable

Code Analysis

  • epd = EPD_1in54: Creates an LCD object.
  • epd.Clear(0xff): Clears the entire screen.
  • epd.fill(0xff): Fills the entire screen with a color.
  • epd.text("RP2350-Touch-ePaper-1.54", 0, 30, 0x00): Writes text on the screen.
  • epd.hline(10, 150, 80, 0x00): Draws a horizontal line.
  • epd.vline(10, 90, 60, 0x00): Draws a vertical line.
  • epd.display(epd.buffer): Refreshes the screen (makes it visible).

Operation Result

  • Run the py files in the 03_GUI folder using Thonny.

    MicroPython-Example-1

04_KEY

Example Description

  • Demonstrates two-button input and common button event recognition under RP2350 MicroPython: BOOT (BOOTSEL special button) and POWER (regular GPIO24).
  • Supported events: down, up, click (single click), double (double click), long (long press), printing event logs to the serial port/Thonny Shell.
  • Example code file: key_events.py (can be used as an importable library or run directly as a main script).

Hardware Connection

  • BOOT: Use the onboard BOOTSEL button.
  • POWER: Use the onboard POWER button (internally connected to GPIO24).
  • Connect the board to the computer via a USB cable and connect the MicroPython interpreter via Thonny.

Code Analysis

  • BootKey: BOOTSEL read wrapper
    • BOOTSEL is not a regular GPIO; MicroPython generally provides a reading interface via rp2.bootsel_button() (or machine.bootsel_button() in some versions).
    • pressed(): Returns whether the button is currently pressed (True means pressed).
  • GpioKey: Regular GPIO button read wrapper
    • Pin(pin, Pin.IN, pull): Configure the specified GPIO as input with pull-up/pull-down.
    • active_low=True: Means pressed is 0, released is 1 (common configuration).
  • Key: Button event state machine (polling-based)
    • debounce_ms: Debounce time. Only when the level change remains stable for longer than this time is the state considered truly changed.
    • double_ms: Double-click detection window. A single-click event is only emitted after waiting for double_ms to confirm no second click occurred.
    • long_ms: Long press threshold. When pressed and held for longer than long_ms, a long event is triggered immediately (without waiting for release).
    • poll(now): Called periodically; internally:
      • Reads the raw level
      • Debounces to obtain a stable state, sending down/up on stable press/release
      • Long press detection: if stable press exceeds long_ms, sends long
      • Single/double click aggregation: on release, counts clicks; after timeout, converts 1 click to click, 2 clicks to double
  • main(banner=False, poll_ms=10): Program entry
    • When banner=True, prints operation tips (suitable for guiding beginners when run as a main script).
    • poll_ms is the polling interval; smaller values are more responsive but consume more CPU (commonly 5–20ms).

Operation Result

  • Run the .py files in the 04_KEY folder directly via Thonny.
    • Open key_events.py in Thonny, ensure the interpreter is set to the MicroPython port of the development board.
    • Click the green Run button; Thonny will send the script to the board for execution.
    • In this case, the script will run as __main__, thus automatically entering main(banner=True), showing prompts and key event output.
    • If you want to use it as a library (import without automatic execution), upload the file to the board and explicitly call key_events.main(...) in your own main.py.
  • Run as main script (auto-execute on power-up)
    • Upload key_events.py to the board root directory and rename it to main.py.
    • After reset, it will first print banner information, then output events on key presses, e.g.:
      • power down / power up / power click
      • power double
      • power long
      • boot down / boot up / boot click ...
  • Run as reusable library (recommended)
    • Keep the filename key_events.py unchanged and upload to the board.
    • Explicitly call in your own main.py:
      • import key_events
      • key_events.main(banner=True) (or banner=False)
  • Stop running
    • Click the Stop button in Thonny, or press Ctrl+C in the Shell/REPL to end the polling loop and return to the interactive prompt.

      mpy_key

05_SHTC3

Example Description

  • Demonstrates reading the SHTC3 temperature and humidity sensor via I2C under RP2350 MicroPython.
  • Supports reading:
    • Temperature (°C)
    • Relative humidity (%RH)

Hardware Connection

  • Sensor is built-in: SHTC3 (I2C). I2C address: default 0x70
  • Connect the board to the computer via a USB cable and connect the MicroPython interpreter via Thonny.

Code Analysis

  • Constants

  • I2C default parameters (see constants at the top of shtc3.py):

    • SHTC3_I2C_NUM: I2C controller number
    • SHTC3_I2C_SCL / SHTC3_I2C_SDA: Default pins
    • SHTC3_I2C_ADDR: I2C address
    • SHTC3_I2C_FREQ: I2C frequency
  • SHTC3 command set:

    • SHTC3_REG_WAKEUP / SHTC3_REG_SLEEP / SHTC3_REG_SOFTRESET / SHTC3_REG_READID
    • SHTC3_MEAS_ALL: Combines stretch/low_power/hum_first to select measurement command
  • SHTC3: Sensor driver class

  • __init__(..., i2c=None, crc_fail_return=(None, None))

    • i2c: Allows externally passing an already created I2C object for sharing the bus with multiple devices
    • crc_fail_return: Return value when CRC check fails (default (None, None))
    • During initialization, executes:
      • wakeup(): Wake up
      • soft_reset(): Soft reset
  • crc8(buffer)

    • Used to verify CRC-8 returned by SHTC3 (polynomial 0x31, initial value 0xFF)
  • read_id()

    • Reads device ID and verifies CRC; returns None if CRC fails
  • measurement(hum_first=False, low_power_meas=False, stretch=False, ...)

    • Reads temperature and humidity once and returns (temperature_c, humidity_rh)
    • Parameter description:
      • low_power_meas=True: Low-power measurement (more power efficient, but repeatability/accuracy is slightly affected, more noticeable on temperature)
      • stretch=True: Enable clock stretching (depends on your I2C bus/driver implementation)
      • hum_first: Which of the two data blocks (temperature/humidity) comes first from the sensor
    • Compatible parameter:
      • hum_frist: retains the typo for compatibility with older examples
  • read(low_power=False, stretch=False, ...)

    • More user-friendly alias: equivalent to measurement(hum_first=False, ...)
  • main(...): Example entry (single-file integrated)

  • When shtc3.py is run directly as a script, it will:

    • Execute main(): loop reading and printing temperature/humidity
    • Ctrl+C to break the loop
  • Parameter description:

    • interval_s: Print interval (seconds)
    • crc_fail_return: Override the driver's default CRC failure return value

Operation Result

  • Method A: Run the .py files in the 05_SHTC3 folder directly via Thonny.

  • Open shtc3.py with Thonny on your computer, and ensure the interpreter is set to the MicroPython port of the development board.

  • Click Run; by default it enters main(), with output similar to:

    • SHTC3 ID: 0x....
    • Temperature: 25.12 °C, Humidity: 45.67 %
  • Stop: Click Stop in Thonny, or press Ctrl+C in the REPL.

  • Method B: Use as importable library (recommended)

  1. Upload shtc3.py to the board's file system (same directory as main.py is most convenient).
  2. Use in your own main.py:
import time
from shtc3 import SHTC3

shtc3 = SHTC3()
while True:
t, rh = shtc3.read()
if t is not None and rh is not None:
print(t, rh)
time.sleep(1)

mpy_shtc3

06_TOUCH

Example Description

  • This example is only for RP2350-Touch-ePaper-1.54.
  • This is a "touch test interface" example: draws 4 touch areas (Area A~D) on the 1.54inch 200×200 e-Paper screen. When touched, the coordinates and area name are displayed at the bottom of the screen and the touch coordinates are printed to the serial port.
  • Screen display uses: first a full refresh to display the "base image", then switches to partial refresh mode for interactive updates (faster, saves time).
  • The touch controller is FT6336U: reads touch point coordinates via I2C, triggers an interrupt via the INT pin to read data, and the main loop retrieves the touch point.
  • Example code files:
    • main.py
    • FT6336U.py

Hardware Connection

  • Connect the board to the computer via a USB cable and connect the MicroPython interpreter via Thonny.

Code Analysis

  • EPD_1in54: E-paper driver + FrameBuffer drawing wrapper (main.py)

    • Inherits framebuf.FrameBuffer: uses buffer as a 200×200 monochrome canvas, then pushes the buffer to the screen.
    • send_command() / send_data(): Write command/data to the screen controller via SPI.
    • ReadBusy(): Poll the BUSY pin to wait for the screen to become idle (must wait during e-Paper refresh).
    • displayPartBaseImage(): Writes the "base image" to both buffers (0x24/0x26) for more stable partial refresh (common practice to reduce ghosting).
    • init(update): Two refresh mode initializations
      • FULL_UPDATE: Full refresh, slow but clean
      • PART_UPDATE: Partial refresh, fast but may have ghosting; requires base image coordination
  • touch_ft6336u: FT6336U touch driver (FT6336U.py)

    • I2C initialization (__init__)
      • machine.I2C(id=1, scl=Pin(7), sda=Pin(6), freq=400_000): Use I2C1, 400kHz.
      • int = Pin(8, IN, PULL_UP): Touch interrupt pin, falling edge triggers callback.
      • rst = Pin(16, OUT): Reset pin; pulls high/low at power-up to reset the chip.
    • init_chip(): Initialize and read ID
      • Read register 0xA3 to get chip ID; example expects 0x64, prints "init ok" or "ID error".
    • Interrupt reading of touch (int_cb / read_touch_data)
      • int_cb() triggers read_touch_data(), which first reads TD_STATUS(0x02) to get the number of touch points, then reads 4 bytes from TOUCH1_X(0x03) to reconstruct x/y.
      • Supports single-touch: only Touch1 is parsed.
    • Main loop point retrieval (get_touch_xy)
      • Returns [{"x":..., "y":...}] when new point is available, then clears point_count so a touch is taken only once (more like an "event" than continuous coordinate stream).
  • Main program flow (main.py)

    • Initialize screen and clear screen: epd = EPD_1in54(), epd.Clear(0xff) (0xff means white).
    • Initialize touch: touch = touch_ft6336u(), will see FT6336U ID-related output on the serial port.
    • Draw static UI: title, dividing lines, 4 rectangular button areas (Area A~D), coordinate display area.
    • Full refresh to show base image: epd.displayPartBaseImage(epd.buffer), then epd.init(epd.part_update) to switch to partial refresh mode.
    • Touch debounce and polling:
      • touch_debounce = 500: only respond to one touch within 500ms to avoid repeated triggers due to interrupts/jitter.
      • touch.get_touch_xy(): when a touch point is obtained:
        • Update the coordinates and area name displayed at the bottom of the screen
        • Highlight the corresponding area with "black background, white text"
        • displayPartial() for partial refresh
        • After 1 second, restore the button appearance and do another partial refresh

Operation Result

  • Method A: Run the .py files in the 06_TOUCH folder directly via Thonny.

    • Select the correct MicroPython interpreter port in Thonny.
    • Upload FT6336U.py to the root directory of the RP2350's built-in MicroPython file system.
    • Open and run main.py.
    • Serial port/Thonny Shell expected output includes:
      • Initializing e-Paper...
      • Initializing touch screen...
      • FT6336U ID = 0x64, FT6336U init ok!
      • On touch, prints: Touch detected: (x, y)
    • Screen expected display:
      • "Touch Test" at the top
      • 4 area buttons (Area A~D)
      • Real-time update of Touch: area name and Pos: coordinates at the bottom
  • Method B: Run as power-on auto-start program

    • Upload main.py and FT6336U.py to the root directory of the RP2350's built-in MicroPython file system.

    • The program will run automatically after reset.

      mpy_touch