Contents
- 1. General requirements
- 2. File structure organization
- 2.1 Folder naming convention
- 2.2 Folder contents
- 2.3 Driver file naming convention
- 3. Driver code file structure
- 3.1 File header comment
- 3.1.1 Key roles of the in-code constants
- 3.2 Standard comment blocks and their contents
- 3.2.1 Module import section
- 3.2.2 Global variable section
- 3.2.3 Function section
- 3.2.4 Custom class section
- 3.2.5 Initialization section
- 3.2.6 Main program section
- 4. Type annotations
- 4.1 Points to note
- 4.2 Concrete examples
- 5. Function design conventions
- 5.1 Design principles
- 5.1.1 Single responsibility
- 5.1.1 Small and explicit
- 5.1.2 Prefer no side effects
- 5.1.3 Testability
- 5.1.4 Resource awareness
- 5.1.5 Interrupt service routines (ISR)
- 5.2 Naming conventions
- 5.2.1 Function naming examples
- 5.2.2 Return value design examples
- 5.3 Function comment conventions
- 5.4 Return value and exception design
- 5.5 Logging/debugging and printing
- 6. Custom class design conventions
- 6.1 Design principles
- 6.1.1 Single responsibility
- 6.1.2 Minimal side effects
- 6.1.3 Explicit dependency injection
- 6.1.4 Testable
- 6.1.5 Error and exception strategy
- 6.2 MicroPython syntax and platform considerations
- 6.3 Class structure and member layout
- 6.4 Class docstring conventions
- 6.5 Method docstring requirements
- 6.5.1 Documenting side effects
- 6.5.2 ISR-safe annotation
- 6.5.3 Callback conventions
- 6.6 Attributes and naming
- 7. Exception handling
- 7.1 General principles
- 7.1.1 Clear and predictable
- 7.1.2 Minimise exposure of low-level exceptions
- 7.1.3 Validate parameters first
- 7.1.4 Never raise exceptions in an ISR
- 7.1.5 Idempotent cleanup
- 7.1.6 Documentation
- 7.2 Exception categories and recommended use
- 7.3 Catching and wrapping
- 7.4 Retries
- 7.5 Resource cleanup
- 7.6 Debug output
- 8. Core design and implementation rules
- 8.1 Extracting general-purpose functions: declare non-hardware / non-business functions outside the class
- 8.2 Exception handling: defining and using custom exception classes
- 8.3 Parameter management: define registers / commands / default parameters as class attributes
- 8.4 Method encapsulation: dividing private / public methods
- 8.5 Interrupt handling: interrupt callbacks and micropython.schedule
- 8.6 Non-blocking execution: implementing periodic / timeout functions with timers
- 8.7 Resource management: releasing hardware resources and context managers
- 8.8 Parameter configuration: wrap in Setter/Getter methods (direct attribute modification forbidden)
- 8.9 Platform compatibility: adapting across hardware platforms
- 8.10 Low-power adaptation: sensor sleep / wake-up and hardware power saving
- 8.11 Type annotations and docstrings: standardised readability
- 8.12 Singleton pattern: avoid initialising hardware more than once
- 9. Requirements for the test file main.py
- 9.1 Core design principles
- 9.2 Initialisation configuration section
- 9.3 Standard metadata comment at the top of the file
- 9.4 Fixed order and meaning of comment blocks
- 9.5 Exception handling and safe shutdown
- 10. Writing README.md
- 10.1 Basic requirements
- 10.2 Example template
- 11. Licence requirements
- 11.1 Licence type
- 11.2 Fixed format of the copyright notice
- 12. Requirements for writing package.json
- 12.1 Template file
- 12.2 Field descriptions
- 12.3 Example file (using bmp280_driver)
- 12.4 Verifying the download
- 12.5 Notes on licences and copyright notices
- Version history
1. General requirements
- Goal: driver code that is readable, reusable and resource-friendly (RAM/flash), with complete documentation and test examples, for MicroPython v1.x (Raspberry Pi Pico / ESP series, etc.).
- Style: follow PEP8 as a reference (4-space indentation, lowercase-with-underscores for functions/variables), but in constrained environments pay more attention to readability and control of memory allocation.
- The code must contain a file header comment at the top (environment, author, license, short description, reference links, time).
- Each driver module should have a single responsibility (one chip / one class of peripheral); avoid cramming the functions of several peripherals into the same file.
- Validate input parameters and raise meaningful exceptions (e.g. ValueError).
- Apart from comments, all raised exceptions and printed output must be in English, and only built-in type annotations supported by MicroPython may be used.
2. File structure organization
2.1 Folder naming convention
- Use lowercase letters plus underscores, e.g.
pca9685_driver - Format:
[sensor name]_driveror[function]_driver
2.2 Folder contents
sensor_driver/ # Project root (repository root, named in lowercase + underscores)
├── code/ # Source root (set as the source root when flashing)
│ ├── sensor.py # Driver implementation file (same name as the sensor, contains the core driver logic)
│ └── main.py # Test/example entry file (may also be named demo.py, demonstrates how to use the driver)
├── package.json # Package configuration file (defines metadata, file mapping, dependencies, etc., for the package management system)
├── README.md # Repository/product description file (same level as code, contains project introduction, usage, etc.)
└── LICENSE # License file (same level as code, declares the open-source license)The purpose of each file is as follows:
| File / folder | Purpose |
|---|---|
| sensor_driver/ | Project root, named according to the [sensor name]_driver or [function]_driver convention; the container for the whole driver package. |
| code/ | Source root; when flashed to the device it is the root directory from which code runs; holds the core driver implementation and example code. |
| code/sensor.py | Driver implementation file, named after the sensor; encapsulates the core logic for sensor initialization, data reading, configuration, etc. |
| code/main.py | Test / example entry file (may also be named demo.py); provides usage examples of the driver and code to verify its functions. |
| package.json | Package configuration file; defines metadata such as the package name, version, file mapping, dependencies and compatible chips / firmware, used for installation via mip. |
| README.md | Project documentation, covering driver features, installation, API reference, caveats, etc., to help developers get started quickly. |
| LICENSE | Open-source license file that states the rules for using, modifying and distributing the project, commonly MIT, Apache-2.0, etc. |
2.3 Driver file naming convention
- Lowercase plus underscores: file names use only lowercase letters, with words separated by underscores.
- Based on the sensor/chip model: prefer naming after the sensor model or chip model.
- Concise and clear: the file name should accurately reflect the driver's function; avoid vague names.
- Avoid conflicts: do not use the same name as a MicroPython built-in module.
Examples
Here are a few examples:
- The sensor model is PCA9685 (a 16-channel PWM controller)
Conforming name: pca9685.py
Rationale: uses the chip model directly, in lowercase, and avoids conflicts with built-in modules (MicroPython built-in modules usually have no such name).
- The sensor model is BMP280 (barometric pressure sensor)
Conforming name: bmp280.py
Rationale: uses the sensor model directly; concise and clear.
- The sensor model is DHT11 (temperature and humidity sensor)
Conforming name: dht11.py
Rationale: uses the sensor model directly. Note that dht.py should be avoided, because there may be several DHT-series sensors (such as DHT22), so naming the specific model is clearer.
- Functional module: a driver module for controlling a motor using the L298N chip. Naming it by function is usually acceptable too, because L298N is not a specific sensor model but a motor driver board (the chip on it is the L298N).
Under the convention, there are two options:
a) If the driver targets the L298N chip, it can be named l298n.py
b) If the driver targets the motor-driving function and may be compatible with several driver chips, it can be named by function, e.g. motor_driver.py; but since the convention prefers the sensor/chip model, l298n.py is more appropriate here.
- The sensor model is HC-SR04 (ultrasonic ranging module)
Conforming name: hc_sr04.py
Rationale: uses the module's model; note the hyphen in the middle, which we convert to an underscore (hyphens are not very friendly in file names, and the convention requires underscore separators).
- The sensor model is MPU6050 (6-axis accelerometer + gyroscope)
Conforming name: mpu6050.py
Rationale: uses the chip model directly.
- Functional module: a driver for controlling an RGB LED strip using WS2812B LEDs
Conforming name: ws2812b.py or neopixel.py (note: MicroPython has a neopixel module, but it is built in, so we must avoid neopixel.py)
Rationale: since a built-in neopixel module already exists, we cannot use neopixel.py, so the chip model ws2812b.py is appropriate. Note, however, that WS2812B is a type of LED and the driver is usually called NeoPixel; but to avoid the conflict we follow the convention and use ws2812b.py.
- The sensor model is DS18B20 (temperature sensor)
Conforming name: ds18b20.py
Rationale: uses the model directly and avoids ds18x20.py (ds18x20 stands for a whole series, and there is a built-in module named ds18x20, so we must not conflict with it; the specific model does not conflict here).
- Note: if a sensor comes in several models but the driver code is generic, we can use a generic name, but we must make sure it does not conflict with a built-in module.
For example: code that drives both DHT11 and DHT22 could be written in one file named dht.py (but note that MicroPython already has a dht module, so dht.py cannot be used). To avoid the conflict, we could name it dht_sensor.py, or use a combination of models? But the convention prefers the sensor model, so to support several models we might name it dht.py, which would conflict with the built-in module and therefore must be avoided.
In fact, MicroPython's built-in dht module already supports DHT11 and DHT22, so we do not need to write our own. If we want to write a more complete driver, to avoid the conflict we could name it dht_driver.py, though this may not fully follow the prefer-the-model convention.
In that case we could consider naming the file dht11_dht22.py, but that is not concise enough. So if a built-in module already exists we usually do not need to write another one; if we must, we can pick a non-conflicting name such as my_dht.py (not recommended, because it does not reflect the function). Alternatively we could state in the documentation that this driver replaces the built-in dht module, but that could cause confusion. So the best practice is to follow the convention, avoid conflicts and not use dht.py.
- If the sensor has no specific model but is based on a generic protocol or function, for example an analog temperature sensor (such as a thermistor), we can name it by function:
For example: analog_temp.py
Rationale: clearly descriptive, but take care to avoid conflicts with built-in modules (there is no built-in module with this name).
Summary: prefer the specific model of the sensor or chip, converted to lowercase letters and underscores. When several sensors share one driver, consider a name that covers these models without conflicting with a built-in module. Also check that it does not share a name with a MicroPython built-in module (such as os, sys, machine, neopixel, dht, ds18x20, etc.).
Below are some common MicroPython built-in modules (partial list) to avoid when naming:
- machine, time, os, sys, math, network, uos, usys, utime, ubinascii, ustruct, ucollections, uhashlib, uheapq, uio, ujson, ure, uzlib, uarray, uasyncio, ucryptolib, uctypes
3. Driver code file structure
3.1 File header comment
Every driver file should start with a uniform template:
# Python env : MicroPython v1.23.0 # Change according to the specific development version/environment
# -*- coding: utf-8 -*-
# @Time : 2025/01/16 10:21 # Use 24-hour time, date format YYYY/MM/DD
# @Author : YourName # Author name
# @File : sensor.py # File name
# @Description : Description of the sensor function (1-2 sentences)
# @License : MIT / Apache2.0 / Custom # State the license explicitlyExample:
# Python env : MicroPython v1.23.0
# -*- coding: utf-8 -*-
# @Time : 2025/01/19 10:00
# @Author : Li Qingshui
# @File : pca9685.py
# @Description : PCA9685 16-channel PWM driver for MicroPython
# @Repository : https://github.com/xxx/yyy
# @License : CC YB-NC 4.0Also declare version and compatibility constants in the code:
__version__ = "0.1.0"
__author__ = "Li Qingshui"
__license__ = "CC YB-NC 4.0"
__platform__ = "MicroPython v1.19+"If the driver can only be used on a particular type of chip (for example, only the RP2040 has PIO; if the driver code, say for a DHT22 sensor, uses PIO to read and write data), a chip constant must also be declared:
__version__ = "0.1.0"
__author__ = "Li Qingshui"
__license__ = "CC YB-NC 4.0"
__platform__ = "MicroPython v1.19+"
__chip__ = "RP2040" Why do this?
- Explicit environment (Python env)
- Purpose: states precisely the environment the code runs in (MicroPython version)
- Necessity: different MicroPython versions have API differences (e.g. changes to the
machinemodule) - Example: I2C interface differences between
v1.19andv1.23can make a driver incompatible
- Encoding declaration (coding)
- Purpose: enforces UTF-8 encoding
- Necessity:
- Avoids garbled Chinese characters (e.g. Chinese comments/documentation)
- Unifies cross-platform encoding behaviour (Windows/Linux differences)
- Timestamp (@Time)
- Purpose: records the last modification time
- Necessity:
- Troubleshooting by version (e.g. "the 2025/01/16 driver misbehaves on ESP32-S3")
- Tracking driver updates (together with Git history)
- Author identification (@Author)
- Purpose: identifies the responsible person and point of contact
- Collaboration value:
- Path for issue feedback (e.g. hardware compatibility problems)
- Basis for copyright ownership (used together with the License)
- File self-description (@File)
- Purpose: prevents misuse of the file
- Real cases:
- When the driver file is copied into another project
- Avoids confusion with drivers of similar names (e.g.
bme280.pyvsbmp280.py)
- Function summary (@Description)
- Purpose: understand what the module does in 15 seconds
- Efficiency gains:
- Developers can reuse it without reading 200 lines of code
- Library management tools can extract documentation automatically
- License declaration (@License)
- Legal necessity:
- MIT/Apache2.0: allow commercial use but require the copyright notice to be kept
- GPL: requires derivative works to be open-sourced
- Custom: constrained by a private corporate agreement
- Legal necessity:
- Repository link (@Repository)
- Purpose: closes the development loop
- Collaboration value:
- Issue feedback (GitHub Issues)
- Version updates (GitHub Releases)
- Contribution guidance (PR submission conventions)
3.1.1 Key roles of the in-code constants
__version__ = "0.1.0" # Semantic versioning: MAJOR.MINOR.PATCH
__author__ = "Li Qingshui" # Author information available at runtime
__license__ = "CC YB-NC 4.0" # Programmatic license check
__platform__ = "MicroPython v1.19+" # Defines the compatibility boundaryThey can be used for dynamic version management: users can check the driver version in their own code to decide whether to upgrade or apply compatibility measures:
import pca9685
# Check version compatibility
if pca9685.__version__ < "0.2.0":
# Handle legacy-version compatibility logic
print("Warning: upgrade the driver to fix PWM jitter")
pca9685.legacy_init()
else:
pca9685.advanced_init()And in automated tool integration: in a build system or package manager, dependencies can be managed by parsing __version__. For example, a project may require a minimum version of 0.3.0 for a certain sensor driver, and the package manager can automatically check and install a version that satisfies it:
# Package manager parses the version automatically
mpip install "pca9685>=0.2.0"For the author field, a common use is extracting the author information when generating documentation automatically:
# Extracted automatically when generating the license file
with open("LICENSES.txt", "a") as f:
f.write(f"{os.path.basename(__file__)} by {__author__}\n")For the license field, in large projects it may be necessary to scan the licenses of all third-party code to ensure compliance with company policy or legal requirements:
if __license__ not in ["MIT", "Apache2.0"]:
raise LicenseError("Incompatible licence type")For the compatibility boundary field, it can be used for runtime environment checks or hardware feature adaptation:
Runtime environment check:
import sys
def check_compatibility():
mp_version = sys.implementation.version
required = tuple(map(int, __platform__.split('v')[-1].split('+')[0].split('.')))
if mp_version < required:
raise EnvironmentError(f"Requires {__platform__}, current is v{mp_version}")Hardware feature adaptation:
if "esp32" in __chip__:
# ESP32-specific optimized code
self._i2c = I2C(scl=Pin(22), sda=Pin(21))
elif "rp2040" in __chip__:
# RP2040-specific configuration
self._i2c = I2C(0, sda=Pin(0), scl=Pin(1))3.2 Standard comment blocks and their contents
In a project, before there is any actual code, the file should look like this:
# Python env : MicroPython v1.23.0 # Change according to the specific development version/environment
# -*- coding: utf-8 -*-
# @Time : 2025/01/16 10:21 # Use 24-hour time, date format YYYY/MM/DD
# @Author : YourName # Author name
# @File : sensor.py # File name
# @Description : Description of the sensor function (1-2 sentences)
# @License : MIT / Apache2.0 / Custom # State the license explicitly
# ======================================== Import modules =========================================
# ======================================== Global variables ============================================
# ======================================== Functions ============================================
# ======================================== Custom classes ============================================
# ======================================== Initialization ==========================================
# ======================================== Main program ===========================================The pca9685.py file is used below as an example:
# Python env : MicroPython v1.23.0
# -*- coding: utf-8 -*-
# @Time : 2025/1/16 10:21 AM
# @Author : Li Qingshui
# @File : pca9685.py
# @Description : Driver module for the PCA9685 16-channel PWM driver chip
# Reference code: https://github.com/adafruit/micropython-adafruit-pca9685/blob/master/pca9685.py
# Parts of this code were originally published by adafruit under the MIT license
# ======================================== Import modules =========================================
# Import packing/unpacking module
import ustruct
# Import time module
import time
# Import hardware module
from machine import I2C
# ======================================== Global variables ============================================
# ======================================== Functions ============================================
# ======================================== Custom classes ============================================
class PCA9685:
"""
This class provides control of the PCA9685 chip; it can set and get the PWM frequency and control the PWM duty cycle.
Attributes:
i2c (I2C): I2C instance used to communicate with the PCA9685 chip.
address (int): I2C address of the PCA9685 chip, default 0x40.
Methods:
reset() -> None:
Reset the PCA9685 module and restore the default settings.
freq(freq: float) -> None:
Set or get the PWM frequency of the PCA9685.
pwm(index: int, on: int, off: int) -> None:
Set or get the PWM signal of the specified servo.
duty(index: int, value: int, invert: bool = False) -> int:
Set or get the duty cycle of the specified servo, with an invert option.
==========================================
PCA9685 class for controlling the PWM signals of up to 16 servos.
Attributes:
i2c (I2C): I2C instance for communicating with the PCA9685.
address (int): I2C address of the PCA9685, default is 0x40.
Methods:
reset() -> None:
Reset the PCA9685 module to default settings.
freq(freq: float) -> None:
Set the PWM frequency of the PCA9685.
pwm(index: int, on: int, off: int) -> None:
Set the PWM signal of the specified servo.
duty(index: int, value: int, invert: bool = False) -> int:
Set the duty cycle of the specified servo and provide invert function.
"""
def __init__(self, i2c: I2C, address: int = 0x40):
"""
Constructor; initializes the PCA9685 instance.
This method initializes I2C communication, sets the PCA9685 address and calls the `reset()` method to reset it.
Args:
i2c (I2C): I2C instance used to communicate with the PCA9685 chip.
address (int, optional): I2C address of the PCA9685, default 0x40.
Raises:
ValueError: If the I2C address is out of range (0x40-0x4F).
==========================================
Constructor to initialize the PCA9685 instance, setting the I2C address and calling the `reset()` method to reset.
Args:
i2c (I2C): I2C instance for communicating with the PCA9685.
address (int, optional): I2C address of the PCA9685, default is 0x40.
Raises:
ValueError: If the I2C address is out of range (0x40-0x4F).
"""
# Check whether the I2C address is between 0x40 and 0x4F
if not 0x40 <= address <= 0x4F:
raise ValueError("Invalid address: %d (must be 0x40-0x4F)" % address)
self.i2c = i2c
self.address = address
self.reset()
def _write(self, address: int, value: int) -> None:
"""
Write one byte of data to the specified address
Args:
address (int): Address to write to.
value (int): Data to write.
==========================================
Write a byte of data to the specified address.
Args:
address (int): Address to write to.
value (int): Value to write.
"""
self.i2c.writeto_mem(self.address, address, bytearray([value]))
def _read(self, address: int) -> int:
"""
Read one byte of data from the specified address
Args:
address (int): Address to write to.
==========================================
Read a byte of data from the specified address.
Args:
address (int): Address to read from.
value (int): Value to read.
"""
return self.i2c.readfrom_mem(self.address, address, 1)[0]
def reset(self) -> None:
"""
Reset the PCA9685 module to the default settings
==========================================
Reset the PCA9685 module to default settings.
"""
# Set the Mode1 register
self._write(0x00, 0x00)
def freq(self, freq: float) -> None:
"""
Set the PWM frequency of the PCA9685.
This method adjusts the PCA9685 prescaler to produce PWM output at the specified frequency.
Args:
freq (float): PWM frequency to set, in Hz.
==========================================
Set the PWM frequency of the PCA9685.
Args:
freq (float): The desired PWM frequency in Hz.
"""
# Compute the prescale value
prescale = int(25000000.0 / 4096.0 / freq + 0.5)
# Read the current Mode1
old_mode = self._read(0x00)
# Enter sleep mode
self._write(0x00, (old_mode & 0x7F) | 0x10)
# Set the prescaler
self._write(0xfe, prescale)
# Restore Mode1
self._write(0x00, old_mode)
time.sleep_us(5)
# Enable auto-increment
self._write(0x00, old_mode | 0xa1)
def pwm(self, index: int, on: int, off: int) -> None:
"""
Set the PWM signal of the specified channel.
This method controls the high and low times of the PWM signal through the specified on and off times.
Args:
index (int): Channel index (0-15).
on (int): High time of the PWM signal.
off (int): Low time of the PWM signal.
==========================================
Set the PWM signal of the specified channel.
Args:
index (int): Index of the channel (0-15).
on (int): High time of the PWM signal.
off (int): Low time of the PWM signal.
"""
data = ustruct.pack('<HH', on, off)
# 0x06 is the address of the LED0 output and brightness control byte
self.i2c.writeto_mem(self.address, 0x06 + 4 * index, data)
def duty(self, index: int, value: int, invert: bool = False) -> int:
"""
Set or get the PWM duty cycle of the specified channel; the value range is 0 to 4095.
Args:
index (int): Channel index (0-15).
value (int): Duty cycle to set, range 0 to 4095.
invert (bool, optional): If True, invert the duty cycle; default False.
Returns:
value (int): Current PWM duty cycle of the channel.
Raises:
ValueError: If the duty cycle value is out of range (0 to 4095).
==========================================
Set the PWM duty cycle of the specified channel, value range is 0 to 4095.
Args:
index (int): Index of the channel (0-15).
value (int): The desired duty cycle, range is 0 to 4095.
invert (bool, optional): If True, invert the duty cycle, default is False.
Returns:
value (int): Current PWM duty cycle of the specified channel.
Raises:
ValueError: If the duty cycle value is out of range (0-4095).
"""
if not 0 <= value <= 4095:
raise ValueError("Invalid value: %d (must be 0-4095)" % value)
if invert:
value = 4095 - value
if value == 0:
self.pwm(index, 0, 4096)
elif value == 4095:
self.pwm(index, 4096, 0)
else:
self.pwm(index, 0, value)
return value
# ======================================== Initialization ==========================================
# ======================================== Main program ===========================================Why do this?
The benefit is that it standardizes key information such as the runtime environment, author and time, file purpose and license, as well as the code structure, making the code easier for others to understand, reproduce and maintain. The uniform sections for imports / globals / functions / classes / initialization / main program also enforce good structure, make it quick to locate functionality and reduce duplication.
3.2.1 Module import section
Purpose: all import statements (module level), grouped and ordered.
What goes here:
- Standard library (
time,ustruct, etc.) - MicroPython hardware modules (
machine,Pin,I2C) - Third-party / same-project modules (
from pca9685 import PCA9685) - If some imports may consume resources or are only used inside a specific function (on low-resource devices), they can be imported on demand inside the function, with a comment noting this here.
Rules:
- Grouping: standard library -> third-party -> local modules.
- Within each group, sort alphabetically or by frequency of use.
- Do not perform operations that may take a long time at the top of the module (e.g.
time.sleep).
Example:
# ======================================== Import modules =========================================
import time
import ustruct
from machine import Pin, I2C
from pca9685 import PCA9685 # Local module, placed last3.2.2 Global variable section
Purpose: module-level constants, default configuration, configurable switches, reusable buffers (bytearray), etc.
What goes here:
- Constants (default I2C address, default frequency)
version,author(if not placed at the top)- A
DEBUGswitch (recommended) - Reusable
bytearraybuffers (e.g.BUF4 = bytearray(4)) to reduce runtime allocation - Type hints can be given as comments (e.g.
DEFAULT_FREQ = 50 # Hz)
Must not go here:
- Creation of complex objects (e.g. opening an I2C object) — put hardware instantiation in the
Initializationsection or the classinit.
Example:
# ======================================== Global variables ============================================
I2C_ADDR_DEFAULT = 0x40
DEFAULT_FREQ = 50 # Hz
DEBUG = False
# Reusable buffer, avoids creating new bytes inside loops
_BUF4 = bytearray(4)# Wrong (creates a new buffer on every call)
# ======================================== Functions ============================================
def read_data():
buf = bytearray(2) # Allocates new memory every time
i2c.readfrom_mem_into(addr, reg, buf)
# ======================================== Global variables ============================================
# Right (globally reused buffer)
BUF2 = bytearray(2)
# ======================================== Functions ============================================
def read_data():
i2c.readfrom_mem_into(addr, reg, BUF2) # Zero memory allocation 3.2.3 Function section
Purpose: module-level utility functions, static helper functions (functionality that does not belong to a class), or pure functions reusable across classes.
What goes here:
- Small, pure utility functions (e.g.
clamp(value, low, high),hex_addr(addr)). - Logic/calculation functions that do no hardware I/O should preferably go here (easier to unit-test).
- Lightweight I/O wrappers (if shared by several classes), but take care with exception wrapping.
Must not go here:
- Functions that use a lot of memory or perform I/O (best placed inside the class, where they can access the instance's reusable buffers).
- Frequent creation of large objects inside functions.
Example:
# ======================================== Functions ============================================
def clamp(x, lo, hi):
"""Clamp x to the range [lo,hi]"""
if x < lo:
return lo
if x > hi:
return hi
return x
def _hex(addr):
"""Return the address as a 0x-formatted string"""
return hex(addr)3.2.4 Custom class section
Purpose: all class definitions (driver classes, helper classes). The order inside each class should also follow a convention.
What goes here:
- The main driver class (e.g.
class PCA9685:) - Higher-level wrapper classes (e.g.
class BusDCMotor:) - Exception classes (
class PCAError(Exception):) may go before the classes or in the constants area at the top of the module
Recommended order inside a class:
- Class-level constants (
ADDR_MIN = 0x40) init(only the necessary initialization)- Public methods (frequency/duty-cycle setting, etc.)
- Private helper methods (starting with
_) deinit()/sleep()/close()last
Notes:
- Avoid long delays in
init; if detection/reset is required, make the retries and delays parameters. - Provide a
docstring(Chinese and English, or Chinese only; Args/Returns/Raises)
Example snippet:
# ======================================== Custom classes ============================================
class PCA9685:
"""
PCA9685 driver class, used to control the PCA9685 PWM expander chip via the I2C interface.
Attributes:
i2c (I2C): MicroPython I2C instance used to communicate with the PCA9685.
address (int): I2C address (default 0x40, range 0x40–0x4F).
debug (bool): Debug mode switch; outputs debug information when enabled.
_buf4 (bytearray): Internal reusable buffer (4 bytes) for I2C data transfer.
Methods:
__init__(i2c, address=0x40, debug=False):
Initialize the driver class, bind the I2C interface and reset the chip.
==========================================
PCA9685 driver class for controlling the PCA9685 PWM expander via I2C.
Attributes:
i2c (I2C): MicroPython I2C instance for communication.
address (int): I2C device address (default 0x40, range 0x40–0x4F).
debug (bool): Debug mode flag for verbose output.
_buf4 (bytearray): Internal reusable buffer (4 bytes) for I2C I/O.
Methods:
__init__(i2c, address=0x40, debug=False):
Initialize driver class with I2C interface and reset device.
"""
ADDR_MIN = 0x40
ADDR_MAX = 0x4F
def __init__(self, i2c, address=0x40, debug=False):
self.i2c = i2c
self.address = address
self.debug = debug
self._buf4 = bytearray(4) # Reusable buffer
self.reset()
...3.2.5 Initialization section
Purpose: module-level or script-level startup configuration and hardware creation (only in example scripts). Keep automatic initialization in library modules to a minimum; concrete hardware instantiation can be done in main.py.
What goes here (in main.py / example scripts):
- Hardware object instantiation (
i2c = I2C(1, ...)) - Configuration and detection (
scan(), address selection) - Setting initialization parameters (
pca.freq(50)) - Safety delays or power-on self-test (short)
In library modules: do not create hardware instances at import time (avoid import side effects). If a convenience factory function is needed, provide something like create_default(i2c_id=1) to be called explicitly.
Example (example script):
# ======================================== Initialization ==========================================
# Power-on delay to let peripherals stabilize
time.sleep(1)
i2c = I2C(1, sda=Pin(6), scl=Pin(7), freq=400000)
addr = next((d for d in i2c.scan() if 0x40 <= d <= 0x4F), None)
pca = PCA9685(i2c, addr)
pca.freq(DEFAULT_FREQ)# ======================================== Initialization ==========================================
# Step 1: power-on delay (wait for peripherals to stabilize)
import time
time.sleep_ms(500) # 500 ms delay
# Step 2: create hardware objects
from machine import I2C, Pin
i2c = I2C(0, sda=Pin(12), scl=Pin(14), freq=400_000)
# Step 3: device detection and selection
devices = i2c.scan()
print("I2C device address:", [hex(d) for d in devices])
if not any(0x40 <= d <= 0x4F for d in devices):
print("Error: PCA9685 not found!")
import sys
sys.exit()
# Step 4: driver initialization
from pca9685 import PCA9685
pca = PCA9685(i2c, 0x40) # Use the default address 0x40
pca.freq(50) # Set 50 Hz PWM frequency
# Step 5: self-test (optional)
if not pca.self_test():
print("Warning: self-test failed, check the connection") 3.2.6 Main program section
Purpose: script entry point, example demos, interactive sequences. Only in example scripts (such as main.py); library modules should not have an automatically running main program.
What goes here:
- The main flow implemented under "Main program" (detect -> test actions -> clean up)
try/except/finallyto make suredeinit()is called or the peripheral is put into a safe state
Must not go here:
- Unbounded infinite loops, unless clearly intended for the example. If a loop is needed, provide an exit condition or a key press to quit.
Example:
# ======================================== Main program ===========================================
try:
# ... test logic ...
pass
except Exception as e:
print("ERROR:", e)
finally:
try:
pca.deinit()
except Exception:
pass4. Type annotations
4.1 Points to note
- Do not use the
typingmodule (MicroPython usually does not include it or supports it only partially). - Only use types or runtime objects that naturally exist in the MicroPython environment as annotations:
int,float,bool,str,bytes,bytearray,list,tuple,dict,None, and hardware classes such asI2C,Pin(from themachinemodule). - For "function types / callbacks", use
callable, which can be checked at runtime (or annotate asobjectand checkcallable(...)at runtime), and state the callback signature and constraints clearly in the docstring. - For "element types of containers", avoid generic forms like
List[int]; annotate withlistand describe the element type in detail in the docstring (e.g. "list of int, unit: ms"). - Annotations must be executable expressions (avoid referring to names that do not exist); if a referenced class comes from
machine, putfrom machine import I2C, Pinat the top of the file so thatI2CandPincan be used directly in annotations. - Static type checking is not the goal — annotations serve to improve readability and act as runtime documentation, together with runtime checks via
isinstance/callable.
Plain-language explanation
Don't use typing:
In many cases MicroPython has no complete typing support (or no such module at all), so don't rely on code like from typing import List, Callable. Writing it may instead raise errors at runtime or simply be ignored.
Only annotate with types that exist at runtime:
Annotations should be real objects that the interpreter can recognize and evaluate: int, float, bool, str, list, dict, and classes like I2C, Pin that you can import from the machine module. That way annotations won't cause import failures, and you can also check them at runtime with isinstance().
For callback/function types, use callable (or object + a runtime check):
If you need to pass in a callback function, don't write a function type that cannot be evaluated. Annotate it as object or callable, then check it in the function body with callable(cb). And state clearly in the docstring the parameters and return format the callback expects (e.g. cb(data: bytes) -> None).
Don't use generic forms to describe container element types:
In MicroPython, generics like List[int] may be unavailable and have no actual runtime effect anyway. Annotate as list and write clearly in the docstring "this is a list of int, unit ms" or similar, so that both people and runtime checks can understand it.
Annotations must be executable expressions:
If you want to annotate with I2C or Pin, first do from machine import I2C, Pin at the top of the file, so that def foo(bus: I2C): won't raise an error at runtime. Don't refer to names not yet defined in the file or classes that don't exist at all.
The purpose of annotations is readability and runtime documentation, not static checking:
In embedded environments we care more about code being stable, lightweight and maintainable at runtime. Annotations are for people to read (and for simple isinstance/callable checks), not for strict type inference by tools such as MyPy.
4.2 Concrete examples
Annotations that can be used directly in function signatures (examples):
- Scalar types:
int,float,bool,str - Binary/buffers:
bytes,bytearray,memoryview - Containers:
list,tuple,dict(element types described in the docstring) - Special:
None(for return types-> None) - Hardware objects:
I2C,Pin(must be imported at the top of the file) - Callbacks/functions: use
callable(orobject, validated withcallable()) - General:
object(when you cannot or do not want to be more precise)
Forbidden (in the MicroPython environment):
typinggeneric forms such astyping.Any,typing.List[int],typing.Optional[...],typing.Callable[...].- Any third-party typing extensions (they reduce portability and may cause NameError on the device).
Example:
from machine import I2C
def set_timer_callback(self, callback: callable, period_ms: int) -> None:
"""
Set the timer callback.
Args:
callback (callable): Callback function with signature func(arg:int) -> None. The callback is invoked in the main loop context (not ISR).
period_ms (int): Timer period, in milliseconds.
Raises:
ValueError: Raised when callback is not callable, or period_ms is invalid.
Notes:
The timer is scheduled in the background and the callback fires at the set period.
This method does not block; the callback should be as short as possible to avoid affecting the main loop.
==========================================
Set timer callback function.
Args:
callback (callable): Callback function, signature func(arg:int) -> None.
It will be invoked in main loop context (not ISR).
period_ms (int): Timer period in milliseconds.
Raises:
ValueError: If callback is not callable or period_ms is invalid.
Notes:
The timer runs in background scheduler, invoking callback periodically.
This method is non-blocking, callback should be lightweight to avoid
slowing down main loop execution.
"""
if not callable(callback):
raise ValueError("callback must be callable")
if period_ms <= 0:
raise ValueError("period_ms must be > 0")
self._cb = callback
self._period = period_ms
5. Function design conventions
5.1 Design principles
- Single responsibility: each function does one thing (read a register / compute a value / format output), which makes it easy to test and reuse.
- Small and explicit: split complex flows into several small functions where possible (separate I/O / parsing / validation).
- Prefer no side effects: where possible, separate code with side effects (I2C/SPI writes/reads / GPIO control) from pure computation.
- Testability: put pure algorithms in separate functions so they can be tested on the host with unittest/pytest (mocking the hardware layer).
- Resource awareness: avoid heavy allocation in hot loops or ISRs; reuse
bytearrays/buffers as much as possible.
5.1.1 Single responsibility
Just as a screwdriver can't be used as a hammer, a function solves only one problem. Tasks such as reading data, computing values and controlling hardware must be split apart, to avoid "do-everything functions" that turn maintenance into a disaster.
# ❌ Wrong: mixed responsibilities (hardware operation + computation + conversion)
def read_temperature():
i2c.writeto(0x40, b'\xF3') # 1. Trigger measurement (hardware operation)
time.sleep_ms(50)
raw = i2c.readfrom(0x40, 2) # 2. Read data (I/O operation)
temp = (raw[0] << 8 | raw[1]) / 256 # 3. Convert raw value (computation)
return round(temp, 1) # 4. Format output (business logic)
# ✅ Right: separated responsibilities
def _trigger_measurement(): # Single responsibility: trigger measurement
i2c.writeto(0x40, b'\xF3')
def _read_raw_data(): # Single responsibility: read raw data
return i2c.readfrom(0x40, 2)
def _convert_to_temp(raw): # Single responsibility: convert raw value
return (raw[0] << 8 | raw[1]) / 256
def get_temperature(): # Compose the atomic functions
_trigger_measurement()
time.sleep_ms(50)
raw = _read_raw_data()
return round(_convert_to_temp(raw), 1) When the sensor protocol changes, only _read_raw_data needs to be modified, without affecting the other logic.
5.1.1 Small and explicit
Putting an elephant in the fridge takes three steps: open the door → put the elephant in → close the door. Complex tasks must be broken down into manageable steps, with no function longer than one screen (20 lines).
# ❌ Wrong: giant function (45 lines!)
def process_sensor_data():
# Step 1: read I2C data (8 lines of code)
# Step 2: verify CRC (15 lines of code)
# Step 3: unit conversion (10 lines of code)
# Step 4: temperature compensation (12 lines of code)
# ✅ Right: split into atomic operations
def _read_sensor_bytes() -> bytes: ... # Focused on reading data
def _verify_crc(data) -> bool: ... # Focused on CRC verification
def _convert_units(raw) -> float: ... # Focused on unit conversion
def _apply_compensation(value) -> float: # Focused on temperature compensation
# Main flow function (as clear as a flowchart)
def get_accurate_reading():
data = _read_sensor_bytes()
if not _verify_crc(data):
raise ValueError("CRC error")
base_value = _convert_units(data)
return _apply_compensation(base_value) 5.1.2 Prefer no side effects
- Pure function: depends only on its arguments and constants, does not read or write external mutable state, does no I/O and does not modify global variables; the same input always gives the same output.
- Side effects: all I/O (I²C/SPI/UART/ADC, GPIO, sleep, logging, random numbers, timestamps, modifying global state) counts as a side effect.
Keep hardware interaction outside the door, and hand only the raw data (raw) and parameters/calibration coefficients to the pure function; the pure function only does computation.
# ❌ Wrong: hardware operation contaminates the computation logic
def calculate_pressure():
i2c.readfrom_mem(addr, 0xF7, buf) # Hardware read (side effect)
raw = (buf[0] << 12) | (buf[1] << 4) | (buf[2] >> 4)
return raw * 0.01 # Computation (pure operation)
# ✅ Right: isolate side effects
# --- Function with side effects (hardware interaction) ---
def _read_pressure_raw() -> int:
i2c.readfrom_mem(addr, 0xF7, buf)
return (buf[0] << 12) | (buf[1] << 4) | (buf[2] >> 4)
# --- Pure function (can be tested independently) ---
def raw_to_pressure(raw_val: int) -> float:
return raw_val * 0.01 # No hardware dependency!
# Combined call
pressure = raw_to_pressure(_read_pressure_raw()) calculate_pressure has the following problems:
- The function depends on hardware (I²C) and cannot be tested on its own on a computer.
- If
i2c.readfrom_memfails, a low-level exception is thrown directly. - The algorithm is tied to the hardware, making porting difficult.
Using the _read_pressure_raw and raw_to_pressure functions has several benefits:
- Hardware and algorithm are decoupled: when changing sensors, only
_read_pressure_rawchanges; theraw_to_pressurealgorithm stays the same. - Exceptions are controllable:
- Hardware exceptions are handled in
_read_pressure_raw; - Computation exceptions are raised separately in
raw_to_pressure.
- Hardware exceptions are handled in
5.1.3 Testability
Think of driver code as an onion — hardware interaction is the outer layer and the core algorithm is the inner layer. Peel off the inner-layer code and you can run automated tests on a PC without depending on hardware.
# ❌ Wrong: coupled to hardware, cannot be tested
def get_humidity():
i2c.writeto(0x27, b'\xE5')
raw = i2c.readfrom(0x27, 2)
return (raw[0] * 256 + raw[1]) * 0.01 # Algorithm and I/O mixed
# ✅ Right: layered design
# Hardware layer (must be tested on the device)
def _fetch_humidity_raw() -> bytes: ...
# Algorithm layer (testable on PC)
def parse_humidity(raw: bytes) -> float:
value = (raw[0] << 8) | raw[1]
if value == 0xFFFF:
raise SensorError("Invalid data")
return value * 0.01
# Business layer
def get_humidity() -> float:
return parse_humidity(_fetch_humidity_raw()) The PC-side test case is then:
# test_humidity.py (runs on PC)
def test_parse_humidity():
# Test normal data
assert parse_humidity(b'\x12\x34') == 46.6
# Test bad data
with pytest.raises(SensorError):
parse_humidity(b'\xFF\xFF') 5.1.4 Resource awareness
Embedded devices have very limited memory (tens of KB to a few hundred KB), unlike a PC/phone with several GB to spare.
So in code:
- Creating objects frequently = constantly wasting memory, like opening bottle after bottle and pouring the water out in the desert;
- Memory fragmentation = like small gaps scattered here and there in a bucket: in the end there is clearly room, yet the water still won't go in.
# ❌ Wrong: allocates new memory on every call
def read_acceleration():
buf = bytearray(6) # Creates a new 6-byte object every time
i2c.readfrom_mem_into(0x68, 0x3B, buf)
return struct.unpack('>hhh', buf) # Creates a tuple as well Problems:
- Every call to
bytearray(6)→ keeps requesting new memory, while old objects wait for garbage collection. - GC (garbage collection) is slow on embedded devices; a stall can cause system jitter.
- After running for a long time, memory fragmentation may occur → new objects cannot get contiguous space, leading to an outright OOM crash.
# ✅ Right: globally reused buffer
ACCEL_BUF = bytearray(6) # Allocated once at startup
def read_acceleration():
i2c.readfrom_mem_into(0x68, 0x3B, ACCEL_BUF)
x = (ACCEL_BUF[0] << 8) | ACCEL_BUF[1] # Parse directly
y = (ACCEL_BUF[2] << 8) | ACCEL_BUF[3]
z = (ACCEL_BUF[4] << 8) | ACCEL_BUF[5]
return (x, y, z) # Return a lightweight tuple Advantages:
- Memory is requested only once; no more frequent new objects inside the loop.
- No intermediate objects from
struct.unpack→ one less memory overhead. - Runs stably, avoiding GC jitter.
🔧 Extended cases
- Sampling sensor data in a loop
TEMP_BUF = bytearray(2)
def read_temperature():
i2c.readfrom_mem_into(0x48, 0x00, TEMP_BUF)
raw = (TEMP_BUF[0] << 8) | TEMP_BUF[1]
return raw / 256.0👉 At 100 samples per second, that is hundreds of thousands per day → the number of memory allocations saved is considerable.
- Network send/receive (avoid frequently allocating socket buffers)
NET_BUF = bytearray(512)
def receive_packet(sock):
n = sock.readinto(NET_BUF) # Fill the buffer directly
return memoryview(NET_BUF)[:n] # Avoid copying👉 memoryview lets you access the data by slicing without creating new objects.
- Stream processing (avoid string concatenation)
# ❌ Inefficient: creates a new string on every concatenation
msg = ""
for i in range(1000):
msg += str(i)
# ✅ Efficient: write into a buffer
from io import StringIO
buf = StringIO()
for i in range(1000):
buf.write(str(i))
msg = buf.getvalue()👉 This optimization is likewise about "avoiding needless new allocations".
5.1.5 Interrupt service routines (ISR)
ISR = do only minimal, deterministic, allocation-free work; push everything that allocates, takes time or may fail to the main loop, or handle it with micropython.schedule.
# ❌ Never allocate memory in an ISR!
def isr_handler():
data = i2c.readfrom(addr, 4) # May trigger GC and cause a crash
# ✅ ISR-safe approach: pre-allocate + operate directly
IRQ_BUF = bytearray(4)
def isr_handler():
i2c.readfrom_into(addr, IRQ_BUF) # Zero memory allocation
value = IRQ_BUF[0] # Use directly - Never allocate memory in an ISR (e.g.
bytearray(...), string concatenation, creating lists/tuples, calling library functions that may allocate). Allocation triggers GC, and GC in interrupt context will crash. - Do not do blocking or time-consuming I/O in an ISR (e.g. I²C/SPI reads/writes, networking, file operations).
- Do not raise exceptions or print in an ISR (
printmay allocate memory). - Keep ISRs as short as possible: do only the most necessary operations — read a pin / record an event / update a counter / write a pre-allocated buffer index / set a flag.
- Push complex or allocating work to the main loop or handle it with
micropython.schedule(runs in the main thread, where allocation is allowed). - Pre-allocate all needed buffers/structures at startup (bytearrays, lists, arrays, etc.), and reserve a minimal memory block for the ISR (
micropython.alloc_emergency_exception_buf(n)). - Briefly disable interrupts to protect shared variables during concurrent access (
machine.disable_irq()/machine.enable_irq(state)) to avoid race conditions.
Case 1: the simplest and most common — encoder/pulse counter (the ISR only increments a count)
Scenario: the GPIO produces a pulse on every rising edge; the ISR only counts, and the main program periodically reads and processes the count.
from machine import Pin
import machine, time
pulse_count = 0 # Global count (the ISR only changes this)
def encoder_isr(pin):
global pulse_count
pulse_count += 1 # Simple integer increment (keep it very short)
# Initialize the pin interrupt
enc_pin = Pin(14, Pin.IN, Pin.PULL_UP)
enc_pin.irq(trigger=Pin.IRQ_RISING, handler=encoder_isr)
# Main loop: periodically read and reset the count (briefly disable interrupts to ensure atomicity)
def read_and_reset_count():
global pulse_count
state = machine.disable_irq()
cnt = pulse_count
pulse_count = 0
machine.enable_irq(state)
return cnt
while True:
time.sleep_ms(200) # Main loop tick
cnt = read_and_reset_count()
if cnt:
print("Pulses in the last 200ms:", cnt) # Safe to print/process in the main thread
Case 2 (key case): "sampling sensor data in a loop" — Data-Ready interrupt + I²C read in the main loop
Scenario: the sensor (e.g. an accelerometer / temperature-humidity sensor) has a DRDY (data ready) pin that raises an interrupt to tell the MCU data is ready. Because I²C is not safe in an ISR, the correct approach is: the ISR records the "event" in a pre-allocated ring event queue; the main loop reads it, uses readfrom_mem_into to read the data into a pre-allocated sample buffer, then parses and stores it.
# Pre-allocated global data structures (allocated once at startup)
from machine import Pin, I2C
import machine, time, micropython
micropython.alloc_emergency_exception_buf(100)
I2C_BUS = I2C(1, scl=Pin(22), sda=Pin(21), freq=400000)
SENSOR_ADDR = 0x68
REG_DATA = 0x3B
EVENT_RING_SIZE = 64
event_head = 0
event_tail = 0
event_buf = bytearray(EVENT_RING_SIZE) # Stores only 0/1 flags, minimal memory use
overflow = False
# Sample buffer: written when the main loop reads I2C (6 bytes each time)
SAMPLE_SIZE = 6
SAMPLE_RING = 128
sample_x = [0] * SAMPLE_RING # Pre-allocated storage for parsed values (integers)
sample_y = [0] * SAMPLE_RING
sample_z = [0] * SAMPLE_RING
sample_write_idx = 0
IRQ_BUF = bytearray(SAMPLE_SIZE) # Temporary buf used by the main loop (reused)
# ISR: very short, only writes a flag into the event ring (no I2C)
def data_ready_isr(pin):
global event_head, overflow
next_head = (event_head + 1) % EVENT_RING_SIZE
if next_head != event_tail: # Write if not full
event_buf[event_head] = 1
event_head = next_head
else:
overflow = True # Ring is full; the main loop is responsible for detecting and logging dropped events
dr_pin = Pin(15, Pin.IN, Pin.PULL_UP)
dr_pin.irq(trigger=Pin.IRQ_FALLING, handler=data_ready_isr)
# Main loop: consume events, safely read I2C and parse (memory allocation allowed)
def pop_event_index():
global event_tail
state = machine.disable_irq()
if event_tail == event_head:
machine.enable_irq(state)
return None
idx = event_tail
event_tail = (event_tail + 1) % EVENT_RING_SIZE
machine.enable_irq(state)
return idx
while True:
ev = pop_event_index()
if ev is None:
# No events: sleep a little (avoid busy-waiting)
time.sleep_ms(10)
continue
# Safely read data via I2C into the pre-allocated buffer IRQ_BUF in the main thread
try:
I2C_BUS.readfrom_mem_into(SENSOR_ADDR, REG_DATA, IRQ_BUF)
except OSError as e:
# Handle hardware errors (retry/log/report, etc.)
print("I2C Read failed", e)
continue
# Parse raw (avoid struct.unpack creating a tuple each time)
x = (IRQ_BUF[0] << 8) | IRQ_BUF[1]
y = (IRQ_BUF[2] << 8) | IRQ_BUF[3]
z = (IRQ_BUF[4] << 8) | IRQ_BUF[5]
# If the data is signed, two's-complement conversion is needed
def to_signed16(v):
return v - 65536 if v & 0x8000 else v
x = to_signed16(x)
y = to_signed16(y)
z = to_signed16(z)
# Store into the pre-allocated sample arrays (no new objects allocated)
sample_x[sample_write_idx] = x
sample_y[sample_write_idx] = y
sample_z[sample_write_idx] = z
sample_write_idx = (sample_write_idx + 1) % SAMPLE_RING
# Next: process the sample_* rings in another task/thread (or process and upload here)
Case 3: push "heavy work" to the main thread — micropython.schedule
An ISR can use it to queue work that needs I/O/allocation to the main thread, while the ISR itself stays very short.
import micropython
from machine import Pin
def heavy_task(arg):
# This function runs in the main thread context and can do I2C, printing, allocation, etc.
# arg is the integer passed in when scheduling
do_i2c_read_and_process()
def irq(pin):
# Ask the main thread to handle it from inside the ISR (returns immediately)
micropython.schedule(heavy_task, 0)
pin = Pin(15, Pin.IN)
pin.irq(trigger=Pin.IRQ_FALLING, handler=irq)
Note: the callback for micropython.schedule must accept one integer argument (you must declare the parameter even if you don't need it).
5.2 Naming conventions
- Function names:
snake_case(lowercase + underscores), starting with a verb to indicate the action, e.g.read_register,set_frequency,calibrate_offset. - Return values: if a function returns a complex structure, consider returning a
tupleordictand explain the meaning of the keys in the docstring.
5.2.1 Function naming examples
Here are some naming examples:
| Category | Wrong name | Right name | Rationale |
|---|---|---|---|
| Register operation | REGread() | read_register() | Verb first + device object |
| Parameter configuration | freqSet(50) | set_frequency(50) | Action and object are clear |
| Calibration | doCalibrate() | calibrate_offset() | States what is calibrated (the offset) |
| Data conversion | tempConvert() | raw_to_celsius() | Shows the direction of conversion (raw value → degrees Celsius) |
| State check | checkState() | is_sensor_ready() | Boolean functions start with is/has |
5.2.2 Return value design examples
Scenario 1: numeric return (simple types)
Note in particular that when multiple values are returned, the actual return type is tuple, so the type annotation should be tuple
def read_temperature() -> float:
"""
Read the current temperature.
Returns:
float: Temperature in degrees Celsius.
Notes:
This function returns a single sample, without filtering or calibration.
==========================================
Read current temperature.
Returns:
float: Temperature in Celsius.
Notes:
This function returns a single raw sample
without filtering or calibration.
"""
return 25.6
# Call
temp = read_temperature() def read_acceleration() -> tuple:
"""
Read 3-axis acceleration.
Returns:
tuple[float]: 3-axis acceleration, in m/s².
==========================================
Read 3-axis acceleration.
Returns:
tuple[float]: acceleration values in m/s².
"""
return 0.12, -0.05, 9.81
# Call
x, y, z = read_acceleration() Scenario 2: structured return (dict)
def get_sensor_status() -> dict:
"""
Get the sensor status.
Returns:
dict: Status dictionary containing the following keys:
- 'temp' (float): Temperature, in ℃
- 'humidity' (float): Relative humidity, in %
- 'error_code' (int): Error code, 0 means normal
- 'timestamp' (int): Time of the last sample, in ms
==========================================
Get sensor status.
Returns:
dict: Status dictionary with keys:
- 'temp' (float): Temperature in ℃
- 'humidity' (float): Relative humidity in %
- 'error_code' (int): Error code, 0 means normal
- 'timestamp' (int): Timestamp of last sample in ms
"""
return {
'temp': 23.4,
'humidity': 45.6,
'error_code': 0,
'timestamp': time.ticks_ms()
}
# Call (access by key)
status = get_sensor_status()
if status['error_code'] != 0:
handle_error(status['error_code']) Scenario 3: efficient data structures (bytes/bytearray)
def read_raw_data(length: int) -> bytearray:
"""
Read raw sensor data (avoiding multiple copies).
Args:
length (int): Number of bytes to read.
Returns:
bytearray: Raw data buffer of length length.
==========================================
Read raw sensor data (zero-copy).
Args:
length (int): Number of bytes to read.
Returns:
bytearray: Raw data buffer of given length.
"""
buf = bytearray(length)
i2c.readfrom_into(0x68, buf)
return buf # Return the buffer directly
# Call (zero-copy processing)
raw = read_raw_data(6)
x = (raw[0] << 8) | raw[1] # Parse directly 5.3 Function comment conventions
Every public function must have a bilingual comment: first a Chinese paragraph (brief description + Args/Returns/Raises/Notes), then a separator line =========================================, followed by the corresponding English description (also containing Args/Returns/Raises). This makes it easy for Chinese- and English-speaking teams to read and for automated extraction.
Some additional details:
Args:,Returns:,Raises:andNotes:stand for the input parameters, returned data, exception handling and necessary remarks respectively- State parameter types clearly (
int,float,bool,bytes,bytearray,I2C, etc.). For unit-sensitive values (such as frequency in Hz or voltage in mV), give the unit:freq_hz (int): frequency, in Hz. - If a function modifies external state or globals, state the side effects explicitly in
Notes(e.g. it changesself._mode, it disables interrupts, etc.). - If a function may be called from an ISR, state
ISR-safe: yes/noinNotesand explain the restrictions (e.g. "must not allocate new memory"). - For asynchronous/scheduled functions (
micropython.schedulecallbacks, etc.), state the signature requirement inNotes(e.g.t: int) and give the reason. - For callback parameters, write out the signature (e.g.
callback(arg: int) -> None) and the calling context (main loop/ISR).
Template example:
def func_name(param1: int, param2: str) -> bool:
"""
One-sentence description of the function in Chinese (concise and clear).
Args:
param1 (int): Meaning and unit (if any) of parameter 1.
param2 (str): Meaning of parameter 2.
Returns:
bool: True means success, False means failure.
Raises:
ValueError: Raised when an argument is invalid.
Notes:
Necessary remarks
==========================================
Short English description of the function (single line).
Args:
param1 (int): Meaning of param1.
param2 (str): Meaning of param2.
Returns:
bool: True if success, False otherwise.
Raises:
ValueError: If arguments invalid.
Notes:
essential issue
"""
...5.4 Return value and exception design
- Clear return values: return explicit types where possible (bool/int/tuple); avoid using
Nonewith mixed meanings. - Use of exceptions:
- Parameter check failure: raise
ValueError. - Hardware communication failure (I2C/SPI) or serious errors: raise
RuntimeErroror a customDeviceError. - Avoid swallowing exceptions (unless they are logged and an explicit error code is returned).
- Parameter check failure: raise
- List in the docstring's
Raisesevery exception type that can be raised and when it occurs.
5.5 Logging/debugging and printing
- Avoid lots of
print()inside libraries. Provide adebugparameter or aloggerinterface instead:if self.debug: print("..."). - Examples and
main.pymay use more detailed printing (to aid debugging), but library functions are silent by default or only output whendebug=True.
For example, our library code is as follows:
class BMP280:
"""
BMP280 sensor driver class; accesses pressure and temperature data via the I2C interface.
Provides initialization, calibration data reading and other functions, so that upper-level applications can compute pressure and temperature.
Attributes:
i2c (I2C): MicroPython I2C instance used to communicate with the BMP280.
address (int): Device I2C address (default 0x77).
debug (bool): Debug switch; outputs internal logs when enabled.
Methods:
__init__(i2c, address=0x77, debug=False):
Initialize the driver class, binding I2C and the address.
_log(message):
Internal log output, effective only in debug mode.
read_calibration() -> bytearray:
Read and return the sensor's calibration register data.
==========================================
BMP280 sensor driver class, communicating via I2C.
Provides initialization and calibration data access
for pressure and temperature calculation.
Attributes:
i2c (I2C): MicroPython I2C instance for communication.
address (int): Device I2C address (default 0x77).
debug (bool): Debug flag, enables internal logging if True.
Methods:
__init__(i2c, address=0x77, debug=False):
Initialize driver class with I2C and address.
_log(message):
Internal logging method, active only in debug mode.
read_calibration() -> bytearray:
Read and return raw calibration register data.
"""
def __init__(self, i2c, address: int = 0x77, debug: bool = False):
"""
Initialize the BMP280 driver class.
Args:
i2c (I2C): An already opened MicroPython I2C instance.
address (int, optional): Device I2C address, default 0x77.
debug (bool, optional): Debug switch, default False.
Notes:
Initialization only binds I2C and the address; it does not access sensor registers.
==========================================
Initialize BMP280 driver.
Args:
i2c (I2C): Opened MicroPython I2C instance.
address (int, optional): Device I2C address, default 0x77.
debug (bool, optional): Enable debug logging, default False.
Notes:
Initialization only binds I2C and address,
does not access sensor registers.
"""
self.i2c = i2c
self.address = address
self.debug = debug
self._log("Initialising BMP280")
def _log(self, message: str) -> None:
"""
Internal log output method.
Args:
message (str): Log message.
Notes:
Outputs only in debug mode. For debugging; does not affect functionality.
==========================================
Internal logging method.
Args:
message (str): Log message.
Notes:
Only prints when debug is enabled.
Intended for debugging, no functional effect.
"""
if self.debug:
print(f"[BMP280] {message}")
def read_calibration(self) -> bytearray:
"""
Read the sensor calibration data.
Returns:
bytearray: 24 bytes of calibration register data.
Notes:
The calibration data is needed to compute the actual temperature and pressure values.
This function only returns the raw bytes, without parsing.
==========================================
Read sensor calibration data.
Returns:
bytearray: 24-byte raw calibration register data.
Notes:
Calibration data must be used to calculate
actual temperature and pressure values.
This function returns raw bytes without parsing.
"""
self._log("Reading calibration registers")
buf = bytearray(24)
self.i2c.readfrom_mem_into(self.address, 0x88, buf)
self._log(f"Calibration data: {bytes(buf)}")
return bufThen, when used:
# In user code
sensor = BMP280(i2c, debug=True) # Enable debugging
sensor.read_calibration()
# Output:
# [BMP280] Initialising BMP280
# [BMP280] Reading calibration registers
# [BMP280] Calibration data: b'\xee\x8f...'
6. Custom class design conventions
6.1 Design principles
- Single responsibility: each class encapsulates only one peripheral or one group of closely related functions (for example:
PCA9685is responsible only for PWM control;BusDCMotoris the high-level motor wrapper). - Minimal side effects: the constructor should not block for long or produce external side effects (such as long waits or external network requests). The constructor only does the necessary validation and lightweight initialisation; operations such as reset/verification are provided as separate methods.
- Explicit dependency injection: do not create hardware bus objects (such as I2C/SPI/Pin) inside the class; pass them in as parameters instead, which makes testing and substitution easier.
- Testable: extract pure logic (calibration/conversion) into pure functions so it can be tested on the host with pytest/unittest; wrap I/O in small, easy-to-mock methods (
_read_reg,_write_reg). - Error and exception strategy: raise
ValueErrorfor parameter errors; raiseRuntimeErroror a customDeviceErrorfor I/O/hardware errors. List allRaises:in the documentation.
6.1.1 Single responsibility
Just as a coffee machine should not double as a microwave, a class should be responsible for only one thing. A sensor driver class should focus on hardware operations (such as reading registers); higher-level functions (such as motor control) should be split into separate classes.
# ❌ Wrong: mixed responsibilities (PWM control + motor logic)
class MotorDriver:
def __init__(self, i2c):
self.pca = PCA9685(i2c) # Low-level PWM controller
self.speed = 0 # High-level motor state
def set_pwm_freq(self, freq): # PWM responsibility
self.pca.freq(freq)
def accelerate(self, target): # Motor responsibility
while self.speed < target:
self.speed += 1
self.pca.duty(0, self.speed)
time.sleep(0.1)
# ✅ Correct: separated responsibilities
class PCA9685: # Responsible only for PWM control
def __init__(self, i2c):
self.i2c = i2c
def set_freq(self, freq): ...
def set_duty(self, channel, duty): ...
class DCMotor: # High-level motor control
def __init__(self, pwm_controller, channel):
self.pwm = pwm_controller # Dependency injection
def accelerate(self, target): ... 6.1.2 Minimal side effects
A constructor is like a birth certificate: it only records the basic information and does not do a medical check-up. Avoid time-consuming operations (such as calibration) in init; these should be invoked through explicit method calls.
# ❌ Wrong: constructor blocks for 3 seconds
class BMP280:
def __init__(self, i2c):
self.i2c = i2c
self._calibrate() # Time-consuming calibration!
def _calibrate(self):
time.sleep(3) # Simulates a long-running operation
# ✅ Correct: initialise on demand
class BMP280:
def __init__(self, i2c):
self.i2c = i2c
self.calibrated = False # Lightweight state flag
def calibrate(self): # Called explicitly
"""Perform calibration (time-consuming operation)"""
time.sleep(3)
self.calibrated = True 6.1.3 Explicit dependency injection
Don't "reinvent the wheel"; use the wheel you are given. The class does not create hardware objects (I2C/SPI) internally; it receives instances passed in from outside.
# ❌ Wrong: creating hardware objects internally
class MPU6050:
def __init__(self):
self.i2c = I2C(1) # Hard-coded pins!
# Resulting problems:
# 1. Cannot reuse an existing I2C bus
# 2. Cannot be mocked for testing
# ✅ Correct: dependency injection
class MPU6050:
def __init__(self, i2c_bus): # Receives an external I2C instance
self.i2c = i2c_bus
# Usage example
shared_i2c = I2C(1)
sensor1 = MPU6050(shared_i2c)
sensor2 = BMP280(shared_i2c) # Bus reuse 6.1.4 Testable
Split the code into "purified water" and "tap water". Pure logic (mathematical calculations) can be tested independently, and hardware interaction is wrapped in small methods that are easy to mock.
# ❌ Wrong: hardware operations coupled with calculation
class SHT30:
def get_temperature(self):
raw = self.i2c.readfrom(0x44, 2) # Hardware operation
return raw[0] * 0.01 - 40.0 # Calculation logic
# Problem: the calculation logic cannot be tested without the hardware
# ✅ Correct: separate hardware from calculation
class SHT30:
def _read_raw(self):
"""Pure hardware operation"""
return self.i2c.readfrom(0x44, 2)
@staticmethod
def raw_to_celsius(raw):
"""Pure calculation logic (independently testable)"""
return (raw[0] << 8 | raw[1]) * 0.01 - 40.0
def get_temperature(self):
raw = self._read_raw()
return self.raw_to_celsius(raw) 6.1.5 Error and exception strategy
Explicit exception types make precise catching and handling easier
- Raise
ValueErrorfor parameter errors - Raise
RuntimeErroror a customDeviceErrorfor I/O or hardware errors - The documentation must list the full exception strategy under
Raises
Use a different "alarm sound" for each kind of error: a parameter error is a short beep, a hardware fault is a long beep.
# ❌ Wrong: ambiguous exception types
class PCA9685:
def set_duty(self, channel, duty):
if not 0 <= duty <= 100:
raise Exception("Invalid duty cycle") # Ambiguous error type
try:
self._write_reg(channel, duty)
except:
raise Exception("Write failed")
# ✅ Correct: categorised exceptions
class PCA9685:
def set_duty(self, channel, duty):
# Parameter error → ValueError
if not 0 <= duty <= 100:
raise ValueError(f"Duty cycle out of range (0-100): {duty}")
try:
# Hardware operation → may raise IOError
self._write_reg(channel, duty)
except OSError as e:
# Convert hardware exception → custom device exception
raise DeviceError("PCA9685 communication failed") from e 6.2 MicroPython syntax and platform considerations
- Type annotations: use only native types available in MicroPython (
int, float, bool, str, bytes, bytearray, list, tuple, dict) and types frommachinesuch asI2C/Pin. Annotate callbacks ascallableand perform acallable()check. - Avoid complex inheritance: prefer simple inheritance (or composition); multiple inheritance and complex metaclasses can cause unforeseeable problems on MicroPython.
- Be careful with dynamic attribute binding: adding attributes dynamically increases memory use; prefer declaring all fields in
init. - Avoid heavyweight standard libraries (such as the large
loggingorconcurrent.futures); use a lightweight debug switch on the device.
Detailed explanation:
MicroPython is a stripped-down version of Python and does not support complex type annotations (such as List[int]). Use only basic types and hardware object types; callback functions must be checked manually for callability.
# ✅ Allowed types
def read_sensor(
i2c: I2C, # machine module type
address: int, # Basic type
timeout: float = 0.1, # Basic type
callback: callable # Annotate the callback with callable
) -> tuple: # Basic container
# Callback safety check
if not callable(callback):
raise TypeError("Callback must be callable")
# Valid operations
data = bytearray(6) # Native byte array
return (data[0], data[1]) # Tuple Also, embedded devices have limited memory, and multiple inheritance can cause memory leaks or unpredictable behaviour; prefer composition (one class containing another) over inheritance.
# ❌ Dangerous multiple inheritance
class SensorBase:
def read_raw(self): ...
class I2CDevice(SensorBase):
def i2c_read(self): ...
class BME280(I2CDevice, SensorBase): # Multiple inheritance
...
# ✅ Safe composition pattern
class I2CAdapter:
def read_register(self, reg): ...
class BME280:
def __init__(self, i2c):
self.i2c = i2c # Composes the I2C adapter
def read_raw(self):
return self.i2c.read_register(0xD0) # Delegated call Furthermore, adding attributes at runtime (such as obj.new_attr=1) consumes extra memory; declare all attributes up front in the constructor.
# ❌ Dynamic attributes (memory killer)
class Sensor:
def __init__(self):
self.temp = 0
s = Sensor()
s.pressure = 1013 # Dynamically added attribute → extra memory allocation
# ✅ __slots__ optimisation
class Sensor:
__slots__ = ('temp', 'humidity') # Fixed attribute slots
def __init__(self):
self.temp = 0
self.humidity = 0
# ✅ Full initialisation in the constructor
class Sensor:
def __init__(self):
self.temp = 0
self.humidity = 0
self.pressure = 0 # Declared up front 6.3 Class structure and member layout
Recommended order of code inside a class (clear and readable):
- Class-level constants (upper case)
init(fast, parameter validation, resource allocation)- Public API (public methods, ordered by frequency of use)
- Property accessors (
@property) or lightweight utility methods - Private methods (prefixed with
_) deinit()/sleep()/close()(resource cleanup)
6.4 Class docstring conventions
Every class must have a bilingual docstring: Chinese first, then a ========================================= separator, then English. The content includes: functional overview, Attributes, Methods, Notes (thread/ISR restrictions, resource requirements (RAM/special pins), compatibility/test board information)
Template:
class PCA9685:
"""
PCA9685 driver class for controlling the PCA9685 PWM expander chip via the I2C interface.
Provides reset, PWM frequency and duty cycle configuration, and multi-channel control; commonly used for servo control, LED dimming and similar applications.
Attributes:
i2c (I2C): MicroPython I2C instance used to communicate with the PCA9685.
address (int): I2C address (default 0x40, range 0x40–0x4F).
debug (bool): Debug output switch; when enabled, internal logs are printed.
Methods:
__init__(i2c, address=0x40, debug=False):
Initialise the driver class, binding the I2C interface and address.
reset() -> None:
Reset the PCA9685 to its default state.
freq(freq_hz: int) -> None:
Set the global PWM frequency (Hz).
duty(index: int, value: int) -> int:
Set the duty cycle of the specified channel; returns the value actually written.
duty_percent(index: int, percent: float) -> None:
Set the duty cycle of the specified channel as a percentage (0.0–1.0).
all_off() -> None:
Turn off output on all channels.
all_on() -> None:
Turn on output on all channels (100% duty cycle).
read_reg(reg_addr: int, nbytes=1) -> bytes:
Read byte data from the specified register.
write_reg(reg_addr: int, data: bytes) -> None:
Write byte data to the specified register.
close() -> None:
Close or release the I2C resource (if needed).
Notes:
- A reusable buffer is created at initialisation to reduce memory allocation.
- I2C operations are not interrupt-safe; do not call them directly in an ISR.
- micropython.schedule can be used to defer calls from an interrupt context.
==========================================
PCA9685 driver class for controlling the PCA9685 PWM expander via I2C.
Provides reset, PWM frequency, and duty cycle configuration, as well as
multi-channel control, commonly used for servos and LEDs.
Attributes:
i2c (I2C): MicroPython I2C instance for communication.
address (int): I2C address (default 0x40, range 0x40–0x4F).
debug (bool): Debug flag, enables logging if True.
Methods:
__init__(i2c, address=0x40, debug=False):
Initialize driver with I2C instance and address.
reset() -> None:
Reset PCA9685 to default state.
freq(freq_hz: int) -> None:
Configure global PWM frequency (Hz).
duty(index: int, value: int) -> int:
Set duty cycle for specific channel, returns actual value written.
duty_percent(index: int, percent: float) -> None:
Set duty cycle as percentage (0.0–1.0) for channel.
all_off() -> None:
Turn off all channels (0% duty).
all_on() -> None:
Turn on all channels (100% duty).
read_reg(reg_addr: int, nbytes=1) -> bytes:
Read bytes from register.
write_reg(reg_addr: int, data: bytes) -> None:
Write bytes to register.
close() -> None:
Close/release I2C resource if applicable.
Notes:
- A reusable buffer is allocated at init to reduce memory allocation.
- I2C operations are not ISR-safe; do not call from interrupts.
- Use micropython.schedule to defer I2C operations in ISR contexts.
"""
6.5 Method docstring requirements
See 5.3 Function docstring conventions
The template is as follows
def func_name(param1: int, param2: str) -> bool:
"""
One-sentence description of the function (concise and clear).
Args:
param1 (int): Meaning of parameter 1 and its unit (if any).
param2 (str): Meaning of parameter 2.
Returns:
bool: True means success, False means failure.
Raises:
ValueError: Raised when an argument is invalid.
Notes:
Necessary notes
==========================================
Short English description of the function (single line).
Args:
param1 (int): Meaning of param1.
param2 (str): Meaning of param2.
Returns:
bool: True if success, False otherwise.
Raises:
ValueError: If arguments invalid.
Notes:
essential issue
"""
...6.5.1 Documenting side effects
Side effects are like a medicine's adverse reactions: besides its main function, a method may quietly change other state (such as modifying registers or switching operating modes). Users must be told explicitly about these "hidden operations".
For example:
- Hardware operations: I²C/SPI communication changes the peripheral's state
- Mode switching: such as waking a sensor from sleep mode
- Memory modification: updating internal buffers or configuration caches
class MPU6050:
def read_acceleration(self) -> tuple:
"""
Read the three-axis acceleration values (x, y, z).
Returns:
tuple: 3-tuple (ax, ay, az), in m/s², range ±2g.
Notes:
- Performs one I2C read transaction (6 bytes).
- Updates the internal `_last_read` timestamp during the call.
- If the sensor is in sleep mode, this method implicitly wakes it up.
==========================================
Read 3-axis acceleration values (x, y, z).
Returns:
tuple: Acceleration values (ax, ay, az) in m/s², ±2g range.
Notes:
- Performs one I2C read transaction (6 bytes).
- Updates internal `_last_read` timestamp.
- Implicitly wakes up the sensor if in sleep mode.
"""
self._wake() # Implicit wake-up operation
self.i2c.readfrom_mem_into(0x68, 0x3B, self._buf)
self._last_read = time.ticks_ms() # Modifies internal state
return self._parse_buf()
6.5.2 ISR-safe annotation
An ISR (interrupt service routine) is like an emergency room: it must be fast and non-blocking. You must state explicitly whether a method can be called safely from an interrupt, to avoid watchdog timeouts or system crashes.
| Safety level | Requirements | Typical scenario |
|---|---|---|
| ISR-safe | <100μs execution, no memory allocation, no blocking | Read triggered by a pin interrupt |
| Main-only | May block or take a long time | Sensor calibration |
For example:
class RotaryEncoder:
def _handle_interrupt(self, pin) -> None:
"""
Rotary encoder interrupt handler.
Args:
pin (Pin): The pin object that triggered the interrupt.
Notes:
- ISR-safe; can be called safely inside an interrupt service routine.
- Execution time < 50 μs.
- No memory allocation.
- No I2C/SPI operations; only an atomic counter update.
==========================================
Interrupt handler for rotary encoder.
Args:
pin (Pin): Pin object that triggered the interrupt.
Notes:
- ISR-safe, can be safely invoked inside ISR.
- Execution time < 50 μs.
- No memory allocation.
- No I2C/SPI operations, only atomic counter update.
"""
self._count += 1 # Atomic operation only
def calibrate_zero(self) -> None:
"""
Perform zero-point calibration.
Notes:
- Main-only, not ISR-safe.
- Contains a blocking delay (10 ms).
- Initiates an I2C write transaction.
- Allocates a temporary buffer.
==========================================
Perform zero-point calibration.
Notes:
- Main-only, not ISR-safe.
- Contains blocking delay (10 ms).
- Initiates an I2C write transaction.
- Allocates a temporary buffer.
"""
buf = bytearray(2) # Memory allocation
6.5.3 Callback conventions
A callback is like the phone call you get after ordering food: you must state clearly who is calling you (parameters), when they call (invocation timing), and how long they can talk (execution limits).
callback_name(arg1: Type, arg2: Type) -> ReturnType class RFIDReader:
def start_listening(
self,
callback: Callable[[int, bytes], None] # Signature: (card ID, UID) -> no return value
) -> None:
"""
Start RFID listening.
Args:
callback (Callable[[int, bytes], None]):
Callback function invoked when a new card is detected.
Function signature: ``def cb(card_id: int, uid: bytes) -> None``.
Notes:
- Invocation context: ISR.
- Execution time must be < 100 μs.
- Memory allocation is forbidden.
- Blocking operations are forbidden.
==========================================
Start RFID listening.
Args:
callback (Callable[[int, bytes], None]):
Callback invoked when a card is detected.
Signature: ``def cb(card_id: int, uid: bytes) -> None``.
Notes:
- Invoked in ISR context.
- Execution time must be < 100 μs.
- No memory allocation allowed.
- No blocking operations.
"""
self._isr_callback = callback
self.irq.trigger(Pin.IRQ_RISING)
def on_data_ready(
self,
callback: Callable[[dict], bool] # Signature: (data dict) -> whether to continue
) -> None:
"""
Set the data-ready callback.
Args:
callback (Callable[[dict], bool]):
Data handler function.
Function signature: ``def cb(data: dict) -> bool``;
return ``True`` to continue acquisition, ``False`` to stop acquisition.
Notes:
- Invocation context: main loop (not ISR).
- May perform JSON serialisation, file writes, network transfers and similar operations.
==========================================
Set data-ready callback.
Args:
callback (Callable[[dict], bool]):
Data handler callback.
Signature: ``def cb(data: dict) -> bool``.
Return ``True`` to continue acquisition,
``False`` to stop acquisition.
Notes:
- Invoked in main loop context (not ISR).
- May perform JSON serialization, file I/O, or network operations.
"""
self._main_callback = callback
6.6 Attributes and naming
- Keep public attributes to a minimum and prefer access through methods (to prevent users from directly overwriting internal state); if an attribute is exposed, provide a read-only view with
@property. - Private attribute names start with a single underscore:
self._buf,self._mode. - Class-level constants are named in all upper case:
REF_CLOCK = 25000000. - For buffers that need to be reused: create
self._buf4: bytearray = bytearray(4)ininitand comment its purpose.
7. Exception handling
7.1 General principles
- Clear and predictable: exceptions raised to callers should have stable semantics (parameter error, communication failure, device error, etc.).
- Minimise exposure of low-level exceptions: catch low-level
OSError/ValueErroretc. and re-raise them as explicit custom or standard exceptions, so the upper layer can handle them easily. - Validate parameters first: validate parameters at the function entry and raise
ValueErrorimmediately, rather than entering an undefined state and failing later. - Never raise exceptions in an ISR: this is unreliable in an ISR and can throw the system into disorder; in an ISR, record an error flag or counter and let the main loop/scheduler handle the exception.
- Idempotent cleanup: ensure resources are safe on the exception path (for example the I2C state, or setting PWM to a safe value), and call
deinit()or restore the default state infinally(where reasonable). - Documentation: every method's docstring must have a
Raises:entry stating which exception is raised when.
7.1.1 Clear and predictable
Exceptions are like traffic lights: a red light must clearly mean "stop" and cannot flicker between red and green. Each exception should have a stable meaning so callers can handle it specifically.
| Exception type | Applicable scenario | Example |
|---|---|---|
| ValueError | Parameter range/type error | set_frequency(-10) |
| TypeError | Parameter type mismatch | write_reg(0x01, "str") |
| OSError | Low-level I/O error (raised as is) | I2C bus error |
| RuntimeError | Device logic error | Sensor self-test failed |
| TimeoutError | Operation timed out | Ultrasonic echo timeout |
| DeviceError | Custom device-level error | Calibration data checksum failed |
7.1.2 Minimise exposure of low-level exceptions
- In MicroPython / embedded systems, low-level hardware operations often raise OSError (for example when an I2C read/write fails).
- If
OSErroris exposed directly to the upper layer:- The user may not know whether it was a "register read failure" or a "file operation failure", because the same
OSErrortype is too broad. - The information is not friendly enough, making the problem hard to locate.
- The user may not know whether it was a "register read failure" or a "file operation failure", because the same
class I2CDevice:
def _read_reg(self, reg: int) -> int:
try:
return self.i2c.readfrom_mem(self.addr, reg, 1)[0]
except OSError as e:
# Wrap the low-level exception
raise DeviceError(
f"Failed to read register 0x{reg:02X}"
) from e # Preserve the original exception chain
class BMP280(I2CDevice):
def read_calibration(self):
try:
return self._read_reg(0x88)
except DeviceError as e:
# Add device context
e.message = f"BMP280 calibration failed: {e.message}"
raise The code wraps the exception in two layers:
Layer 1: convert OSError into DeviceError in the low-level driver
class I2CDevice:
def _read_reg(self, reg: int) -> int:
try:
return self.i2c.readfrom_mem(self.addr, reg, 1)[0]
except OSError as e:
raise DeviceError(
f"Failed to read register 0x{reg:02X}"
) from e # Preserve the original exception chain- What the upper layer sees is a DeviceError, not "a baffling OSError".
from ealso preserves the original exception chain, making it easier to trace during debugging.
Layer 2: add context in the specific device class
class BMP280(I2CDevice):
def read_calibration(self):
try:
return self._read_reg(0x88)
except DeviceError as e:
e.message = f"BMP280 calibration failed: {e.message}"
raise
This adds the device name and functional context.
The error message the end user sees will be clearer:
BMP280 calibration failed: failed to read register 0x88rather than an abstract OSError.
7.1.3 Validate parameters first
def configure_sensor(
mode: int,
oversampling: int,
filter_coeff: int
):
# First line of defence: parameter validation
if mode not in (0, 1, 3):
raise ValueError("Mode must be 0/1/3")
if oversampling > 5:
raise ValueError("Oversampling rate cannot exceed 5")
if filter_coeff not in [0, 2, 4, 8, 16]:
raise ValueError("Invalid filter coefficient")
# Execute the core logic safely
self._write_reg(0xF4, (mode << 5) | (oversampling << 2))
self._write_reg(0xF5, filter_coeff) 7.1.4 Never raise exceptions in an ISR
- The ISR runs in a special environment
- As soon as an interrupt fires, the CPU immediately suspends the current task and jumps into the ISR.
- An ISR must be very short and very fast, otherwise it will stall the whole system.
- Raising an exception is too expensive
- Raising an exception requires stack unwinding and memory allocation, which are unsafe in an ISR.
- In MicroPython, dynamic memory allocation is also forbidden in an ISR, so raising an exception is very likely to crash the system outright.
- The correct approach
- In the ISR, do only the most essential, shortest logic.
- If an error occurs, do not raise an exception; instead set a flag bit and leave it to the main loop to handle.
class Encoder:
def __init__(self):
self._count = 0
self._error_flags = 0 # Error flag bits
# ISR interrupt handler
def _isr_handler(self, pin):
try:
a = self.pin_a.value()
b = self.pin_b.value()
# Core counting logic...
except Exception:
# Never raise! Record an error flag
self._error_flags |= 0x01
# Checked from the main loop
def check_errors(self):
if self._error_flags:
raise DeviceError(f"Encoder error: flags={bin(self._error_flags)}") - In the ISR: do not raise an exception → only change a flag bit, e.g.
_error_flags |= 0x01. - Main loop: periodically check
_error_flags; if there is an error, raise the exception there and handle it.
Error flag bit design:
| Bit | Meaning | Trigger condition |
|---|---|---|
| 0 | Pin state conflict | A/B pins change simultaneously |
| 1 | Count overflow | More than 1000 interrupts within 1 second |
| 2 | Watchdog warning | ISR execution exceeds 50μs |
7.1.5 Idempotent cleanup
In mathematics, idempotent means doing the same operation once or many times has the same effect:
👉 Press a light switch once and the light is off; press it ten times and it is still off: the end result is the same.
👉 But "increase brightness by 10%" is not idempotent: pressing it several times makes the result accumulate.
In a program's exception handling and cleanup logic, the same cleanup function may sometimes be called repeatedly (for example once in the exception handler and again in finally).
If these cleanup functions are not idempotent, problems can arise:
- First call: releases the resource ✅
- Second call: without proper protection, releasing a resource that has already been released may raise an error ❌
So cleanup code must be safe to execute repeatedly; this is "idempotent cleanup".
Resource cleanup in exception handling must be safe to execute repeatedly.
class MotorController:
def move_to_position(self, pos: int):
self.enable() # Power on
try:
# Operations that may fail
self._set_target(pos)
self._wait_until_done(timeout=10.0)
except TimeoutError:
# 1. Log the fault
self.log_error("Move timed out")
# 2. Safe stop (idempotent operation)
self.emergency_stop()
raise
finally:
# 3. Always enter a safe state
self._release_brake() # Can be called repeatedly
self._set_power(0) # Power off
def emergency_stop(self):
"""Safe stop that can be called repeatedly"""
if self._power > 0:
self._brake_pin.value(1)
self._power = 0 emergency_stop() contains:
if self._power > 0:
self._brake_pin.value(1)
self._power = 0👉 This is the idempotent pattern. Whether you call it once or 10 times, as long as _power is already 0 the brake will not be applied again: no error, and no effect on the result.
The same goes for _release_brake() and _set_power(0) in finally:
👉 even if the resource has already been released, running it once more does no harm.
7.1.6 Documentation
Every method must declare in its documentation the exceptions it may raise and their trigger conditions.
class UltrasonicSensor:
def measure_distance(self, max_cm: int = 400) -> float:
"""
Measure distance with the ultrasonic sensor.
Args:
max_cm (int, optional): Maximum detection distance (centimetres). Default 400.
Returns:
float: Actual measured distance (centimetres).
Raises:
ValueError: If ``max_cm`` exceeds the hardware limit (>500 cm).
TimeoutError: No echo signal received within the time corresponding to ``max_cm``.
DeviceError: The sensor fails to respond 3 times in a row.
Notes:
- Uses blocking measurement.
- Exceeding the threshold raises an exception rather than returning None.
==========================================
Measure distance using ultrasonic sensor.
Args:
max_cm (int, optional): Maximum detection range in centimeters. Default 400.
Returns:
float: Measured distance in centimeters.
Raises:
ValueError: If ``max_cm`` exceeds hardware limit (>500 cm).
TimeoutError: No echo received within time corresponding to ``max_cm``.
DeviceError: Sensor failed to respond 3 times consecutively.
Notes:
- Blocking measurement method.
- Exceptions are raised on failure instead of returning None.
"""
if max_cm > 500:
raise ValueError("Maximum distance must not exceed 500cm")
try:
# Send a pulse and wait for the echo...
pass
except OSError as e:
self._error_count += 1
if self._error_count >= 3:
raise DeviceError("Sensor not responding") from e
raise TimeoutError("Echo timeout")
7.2 Exception categories and recommended use
ValueError: parameter validation errors, e.g. index out of range, frequency outside the allowed range, wrong type (not callable), etc.RuntimeErroror a customDeviceError(inheriting fromRuntimeError): hardware communication failures, e.g. I2C/SPI read/write failure, timeout, CRC check failure.- Custom exceptions (e.g.
PCA9685Error,SensorError): unrecoverable or severe faults, so the upper layer can distinguish them by type and apply different strategies. debugorreturn: warnings/non-fatal situations; a return value ordebugoutput is enough- Write the error to a pre-allocated buffer or set
self._err_flag: "errors" in an ISR; do not raise exceptions or perform blocking I/O in an ISR
7.3 Catching and wrapping
- In all low-level I/O methods (such as
_write,_read), catchOSErrorand raiseDeviceErrororRuntimeError, keeping the original information for debugging. - Avoid letting
OSErrorpropagate directly to callers outside the library (theOSErrorinformation returned by different firmware is not consistent); wrapping it uniformly is more robust.
7.4 Retries
- For transient I2C/SPI errors, limited retries can be implemented, e.g. 2-3 times, with a small, configurable interval.
- Provide optional parameters
retries=1,delay_ms=5. By default, do not retry indefinitely, to avoid blocking the main loop.
7.5 Resource cleanup
- Use
try/except/finallyaround operations that may raise exceptions, to ensure the peripheral is put into a safe state (for example, setting all PWM outputs to 0). deinit()should be idempotent (calling it multiple times is harmless). The main program'sfinallyblock should calldeinit().
7.6 Debug output
- Avoid the large
logginglibrary in MicroPython; use a lightweightdebugswitch to controlprint(). - Exception messages should be concise and contain the key information (function/register/channel/address), for example:
"I2C write failed reg=0x06 ch=3: [Errno]". - On error, more detailed context (call arguments, internal state) can be printed in debug mode.
8. Core design and implementation rules
In MicroPython sensor driver development, embedded hardware resources are limited, platforms differ significantly, and low-level operations such as interrupts and timers easily cause conflicts. Traditional development often suffers from rampant hard-coding, difficult error localisation, resource leaks and unstable data. The following core design and implementation rules are therefore defined around the core principles of "cohesive hardware logic, concise external interface, thorough exception handling, closed-loop resource management". They cover every dimension, including extracting functions, exception handling, parameter management and hardware adaptation, with the aim of improving driver maintainability, robustness and portability, and meeting the non-blocking, low-power, high-reliability requirements of embedded use.
8.1 Extracting general-purpose functions: declare non-hardware / non-business functions outside the class
A sensor driver class should focus on the core hardware interaction logic (such as register reads/writes, interrupt configuration, data acquisition). General-purpose, reusable functions that have nothing to do with the hardware (such as data format conversion, CRC checking, value calibration, unit conversion) should be extracted and declared outside the class, which lowers the coupling of the class and improves function reuse.
# -------------------------- General-purpose utility functions outside the class --------------------------
# Function: SHT30 sensor CRC8 check (unrelated to hardware interaction, data checking only)
def sht30_crc8(data: bytes) -> int:
"""
SHT30 CRC8 checksum calculation
:param data: byte data to check (e.g. raw data from register reads/writes)
:return: the calculated CRC8 value
"""
POLYNOMIAL = 0x31
crc = 0xFF
for byte in data:
crc ^= byte
for _ in range(8):
if crc & 0x80:
crc = (crc << 1) ^ POLYNOMIAL
else:
crc <<= 1
crc &= 0xFF
return crc
# Function: convert raw temperature value to degrees Celsius (general numeric conversion, hardware-independent)
def raw_temp_to_celsius(raw_temp: int) -> float:
return -45.0 + 175.0 * raw_temp / 65535.0
# Function: convert raw humidity value to percent (general numeric conversion)
def raw_hum_to_percent(raw_hum: int) -> float:
return 100.0 * raw_hum / 65535.0
# -------------------------- Sensor core class --------------------------
class SHT30:
def __init__(self, i2c, addr=0x44):
self.i2c = i2c
self.addr = addr
# Hardware-related logic is implemented only inside the class
self._is_init = False8.2 Exception handling: defining and using custom exception classes
Avoid raising the generic Exception directly. Define dedicated custom exception classes for the typical exception scenarios of a sensor driver (such as communication failure, invalid parameter, data check failure, hardware not initialised). This makes errors faster to locate and lets the business layer catch and handle exceptions precisely.
# -------------------------- Custom exception classes --------------------------
class SensorError(BaseException):
"""Base sensor exception (parent class of all sensor exceptions)"""
pass
class SensorCommunicationError(SensorError):
"""Sensor communication exception (e.g. I2C/SPI read/write failure)"""
def __init__(self, msg: str = "Sensor communication failed"):
super().__init__(msg)
class SensorInvalidParamError(SensorError):
"""Invalid sensor parameter (e.g. sampling rate out of range, wrong address)"""
def __init__(self, param: str, value, valid_range: tuple):
super().__init__(f"Invalid value {value} for parameter {param}, valid range: {valid_range}")
class SensorDataError(SensorError):
"""Sensor data exception (e.g. CRC check failure, data outside a reasonable range)"""
def __init__(self, msg: str = "Sensor data check failed"):
super().__init__(msg)
# -------------------------- Exception usage example (integrated into the sensor class) --------------------------
class SHT30:
def __init__(self, i2c, addr=0x44):
self.i2c = i2c
# Validate the address
if addr not in (0x44, 0x45):
raise SensorInvalidParamError("addr", addr, (0x44, 0x45))
self.addr = addr
def _write_cmd(self, cmd: bytes):
"""Private method: write a command (hardware interaction)"""
try:
self.i2c.writeto(self.addr, cmd)
except OSError as e:
raise SensorCommunicationError(f"I2C write failed: {e}") from e8.3 Parameter management: define registers / commands / default parameters as class attributes
Declare the sensor's fixed hardware parameters (such as register addresses, communication commands) and default configuration parameters (such as sampling rate, precision, timeout) as class attributes (upper-case constant style), instead of hard-coding them inside methods, so they can be maintained and changed in one place.
class SHT30:
# -------------------------- Class attributes (fixed hardware parameters) --------------------------
# Register/command addresses (SHT30 hardware specification)
CMD_MEASURE_HIGH_REP = b'\x2C\x06' # High-repeatability measurement command
CMD_READ_STATUS = b'\xF3\x2D' # Read status register command
CMD_SOFT_RESET = b'\x30\xA2' # Soft reset command
# Default configuration parameters
DEFAULT_SAMPLING_RATE = 1000 # Default sampling interval (ms)
DEFAULT_TIMEOUT = 500 # Default communication timeout (ms)
# Data ranges (for validation)
TEMP_RANGE = (-45.0, 125.0) # Valid temperature range
HUM_RANGE = (0.0, 100.0) # Valid humidity range
def __init__(self, i2c, addr=0x44):
self.i2c = i2c
if addr not in (0x44, 0x45):
raise SensorInvalidParamError("addr", addr, (0x44, 0x45))
self.addr = addr
self._is_init = False
def soft_reset(self):
"""Public method: sensor soft reset"""
self._write_cmd(self.CMD_SOFT_RESET) # Use the class attribute directly, avoid hard-coding8.4 Method encapsulation: dividing private / public methods
| Method type | Definition rule | Use cases | Naming style |
|---|---|---|---|
| Public method | Core functionality exposed externally, called by the business layer | Initialisation, data reading, parameter configuration, reset, etc. | Lower case + underscores (e.g. read_temp_hum()) |
| Private method | Helper logic called only inside the class; external calls are forbidden | Low-level hardware reads/writes, data parsing, validation, etc. | Leading single underscore + lower case + underscores (e.g. _read_raw_data()) |
class SHT30:
# (Class attributes, custom exceptions and functions outside the class omitted, see above)
def init(self):
"""Public method: sensor initialisation (exposed externally)"""
self.soft_reset()
self._is_init = True
def read_temp_hum(self):
"""Public method: read temperature and humidity (core external function)"""
if not self._is_init:
raise SensorError("Sensor not initialised")
# Call private methods to perform the low-level logic
raw_data = self._read_raw_data()
temp, hum = self._parse_raw_data(raw_data)
# Data validation
self._validate_data(temp, hum)
return temp, hum
# -------------------------- Private methods (called only inside the class) --------------------------
def _read_raw_data(self):
"""Private method: read raw data (low-level hardware interaction)"""
self._write_cmd(self.CMD_MEASURE_HIGH_REP)
try:
raw_data = self.i2c.readfrom(self.addr, 6) # Read 6 bytes of raw data
except OSError as e:
raise SensorCommunicationError(f"I2C read failed: {e}") from e
return raw_data
def _parse_raw_data(self, raw_data: bytes):
"""Private method: parse raw data into temperature and humidity values"""
# Split out the raw temperature and humidity values and CRCs
raw_temp = (raw_data[0] << 8) | raw_data[1]
crc_temp = raw_data[2]
raw_hum = (raw_data[3] << 8) | raw_data[4]
crc_hum = raw_data[5]
# Check CRC (calls a general-purpose function outside the class)
if sht30_crc8(raw_data[:2]) != crc_temp or sht30_crc8(raw_data[3:5]) != crc_hum:
raise SensorDataError("CRC check failed, data is invalid")
# Convert to actual values (calls general-purpose functions outside the class)
temp = raw_temp_to_celsius(raw_temp)
hum = raw_hum_to_percent(raw_hum)
return temp, hum
def _validate_data(self, temp: float, hum: float):
"""Private method: check that the data is within the valid range"""
if not (self.TEMP_RANGE[0] <= temp <= self.TEMP_RANGE[1]):
raise SensorDataError(f"Temperature {temp}°C outside valid range {self.TEMP_RANGE}")
if not (self.HUM_RANGE[0] <= hum <= self.HUM_RANGE[1]):
raise SensorDataError(f"Humidity {hum}% outside valid range {self.HUM_RANGE}")8.5 Interrupt handling: interrupt callbacks and micropython.schedule
When a sensor interrupt fires, the interrupt callback must follow these rules:
- The callback performs only lightweight operations (such as flagging the interrupt state, recording a timestamp); time-consuming operations (such as I2C reads/writes, complex calculations) are forbidden;
- Use
micropython.scheduleto schedule the core processing logic to run in the main loop, avoiding interrupt-context conflicts (such as a busy hardware bus or memory access errors); - The callback keeps only the necessary hardware object / state parameters, keeping the interrupt context simple.
import micropython
from machine import Pin
class SHT30:
# (Attributes/methods above omitted)
def __init__(self, i2c, addr=0x44, int_pin: int = None):
self.i2c = i2c
self.addr = addr
self._is_init = False
self._int_flag = False # Interrupt flag
self._int_pin = None
# Configure the interrupt pin (if provided)
if int_pin is not None:
self._init_interrupt(int_pin)
def _init_interrupt(self, int_pin: int):
"""Private method: initialise the interrupt pin"""
self._int_pin = Pin(int_pin, Pin.IN, Pin.PULL_UP)
# Configure a falling-edge interrupt and bind the callback
self._int_pin.irq(
trigger=Pin.IRQ_FALLING,
handler=self._int_callback # Interrupt callback
)
def _int_callback(self, pin):
"""Interrupt callback (lightweight operation)"""
# Only flag the interrupt state; the core logic is scheduled via schedule
micropython.schedule(self._handle_interrupt, None)
def _handle_interrupt(self, _):
"""Interrupt handling logic scheduled into the main loop (core operation)"""
if not self._int_flag:
self._int_flag = True
# Perform time-consuming operations (e.g. read data, notify the business layer)
try:
temp, hum = self.read_temp_hum()
print(f"Interrupt fired: temperature {temp:.2f}°C, humidity {hum:.2f}%")
except SensorError as e:
print(f"Interrupt handling failed: {e}")
self._int_flag = False8.6 Non-blocking execution: implementing periodic / timeout functions with timers
Avoid using time.sleep(), which blocks the main loop. Periodic sensor sampling, timeout detection and similar scenarios must be implemented as non-blocking functions with machine.Timer, using a state machine / flags to manage execution state, so that the main loop can handle other tasks in parallel.
from machine import Timer
class SHT30:
# (Attributes/methods above omitted)
def __init__(self, i2c, addr=0x44, int_pin: int = None):
self.i2c = i2c
self.addr = addr
self._is_init = False
self._int_flag = False
self._int_pin = None
self._timer = None # Timer object
self._latest_temp = None # Latest temperature value
self._latest_hum = None # Latest humidity value
if int_pin is not None:
self._init_interrupt(int_pin)
def start_periodic_sampling(self, interval: int = None):
"""Public method: start non-blocking periodic sampling"""
if not self._is_init:
self.init()
# Use the default sampling interval (class attribute)
interval = interval or self.DEFAULT_SAMPLING_RATE
# Initialise the timer (periodic mode)
self._timer = Timer(-1) # Virtual timer (adjust for the hardware)
self._timer.init(
period=interval,
mode=Timer.PERIODIC,
callback=self._sampling_callback
)
def stop_periodic_sampling(self):
"""Public method: stop periodic sampling"""
if self._timer is not None:
self._timer.deinit()
self._timer = None
def _sampling_callback(self, timer):
"""Timer callback: non-blocking sampling (core logic)"""
try:
# Sample and update the latest values (no sleep, non-blocking)
self._latest_temp, self._latest_hum = self.read_temp_hum()
except SensorError as e:
print(f"Periodic sampling failed: {e}")
# -------------------------- Main loop example (non-blocking check) --------------------------
if __name__ == "__main__":
from machine import I2C, Pin
# Initialise I2C
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
# Initialise the sensor
sht30 = SHT30(i2c, addr=0x44)
# Start non-blocking periodic sampling (once per second)
sht30.start_periodic_sampling(1000)
# Main loop (can handle other tasks in parallel, no blocking)
while True:
# Print the latest sampled values
if sht30._latest_temp is not None:
print(f"Main loop: temperature {sht30._latest_temp:.2f}°C, humidity {sht30._latest_hum:.2f}%")
# Other main-loop tasks (example: check buttons)
# ...8.7 Resource management: releasing hardware resources and context managers
In MicroPython, hardware resources (I2C/SPI/Pin/Timer/interrupts) that are not released properly easily lead to resource leaks and hardware conflicts (such as a timer left occupied, or a pin not released). You must:
- Define a public
deinit()method that releases all hardware resources in one place; - Implement a context manager (
enter/exit) so that thewithstatement manages the resource lifecycle automatically; - Never leave timers / interrupts open before the driver is destroyed.
class SHT30:
# (Attributes/methods above omitted)
def deinit(self):
"""Public method: release all hardware resources"""
# Stop the timer
if self._timer is not None:
self._timer.deinit()
self._timer = None
# Disable the interrupt
if self._int_pin is not None:
self._int_pin.irq(handler=None) # Unbind the interrupt callback
self._int_pin = None
# Reset state
self._is_init = False
self._int_flag = False
self._latest_temp = None
self._latest_hum = None
def __enter__(self):
"""Context manager: initialise on entry"""
self.init()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager: release resources on exit"""
self.deinit()
# If there is an exception, return False so it propagates upward
return False
# -------------------------- Usage example --------------------------
if __name__ == "__main__":
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
# The context manager manages resources automatically
with SHT30(i2c, addr=0x44, int_pin=2) as sht30:
sht30.start_periodic_sampling(1000)
for _ in range(5):
print(f"Temperature: {sht30._latest_temp:.2f}°C")
time.sleep(1)
# After leaving the with block, resources have been released automatically
print("Resources released: ", sht30._timer is None) # Prints True8.8 Parameter configuration: wrap in Setter/Getter methods (direct attribute modification forbidden)
External code must not modify the driver's configuration attributes directly (such as _sampling_rate). You must:
- Define public
set_xxx()/get_xxx()methods that wrap parameter configuration; - Add parameter validity checks in the Setter methods;
- Make key configuration changes take effect automatically (e.g. restart the timer after the sampling rate changes).
class SHT30:
# (Attributes/methods above omitted)
def __init__(self, i2c, addr=0x44, int_pin: int = None):
# New private configuration attribute
self._sampling_rate = self.DEFAULT_SAMPLING_RATE # Sampling rate (ms)
# Other initialisation logic...
def set_sampling_rate(self, rate: int):
"""Public Setter: set the sampling rate (ms)"""
# Validate the parameter
if not (100 <= rate <= 10000): # Valid range 100ms~10s
raise SensorInvalidParamError("sampling_rate", rate, (100, 10000))
self._sampling_rate = rate
# If sampling has started, restart the timer so the new rate takes effect
if self._timer is not None:
self.stop_periodic_sampling()
self.start_periodic_sampling(rate)
def get_sampling_rate(self):
"""Public Getter: get the current sampling rate"""
return self._sampling_rate
# -------------------------- Usage example --------------------------
sht30 = SHT30(i2c, addr=0x44)
sht30.init()
sht30.set_sampling_rate(2000) # Sample once every 2 seconds
print(f"Current sampling interval: {sht30.get_sampling_rate()}ms") # Prints 2000
# Direct modification forbidden: sht30._sampling_rate = 50 (violates the standard, no validation)8.9 Platform compatibility: adapting across hardware platforms
MicroPython runs on different hardware platforms such as ESP32/ESP8266/RP2040. The driver must:
- Adapt to hardware differences between platforms (such as Timer numbers, I2C/SPI bus numbers, pin definitions);
- Define platform detection logic that adapts parameters automatically;
- Avoid platform-specific APIs (such as the differences between ESP32's
machine.RTCand RP2040'smachine.RTC).
import sys
class SHT30:
# (Attributes/methods above omitted)
def __init__(self, i2c=None, addr=0x44, int_pin: int = None):
# Automatically pick a default I2C bus (cross-platform)
if i2c is None:
platform = sys.platform
self._log(2, f"Auto-detected platform: {platform}")
if platform == "esp32":
# ESP32 default I2C0 (scl=22, sda=21)
self.i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
elif platform == "rp2":
# RP2040 default I2C0 (scl=1, sda=0)
self.i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
elif platform == "esp8266":
# ESP8266 default I2C (scl=5, sda=4)
self.i2c = I2C(scl=Pin(5), sda=Pin(4), freq=100000) # ESP8266 supports only 100kHz
else:
raise SensorError(f"Unsupported platform: {platform}, pass in an I2C object manually")
else:
self.i2c = i2c
# Other initialisation logic...
# -------------------------- Usage example --------------------------
# No need to initialise I2C manually; the driver adapts to the platform automatically
sht30 = SHT30(addr=0x44)
sht30.init()8.10 Low-power adaptation: sensor sleep / wake-up and hardware power saving
Data acquired by sensors is easily affected by noise (such as jumps in temperature/humidity, or bounce in contact sensors). The driver must:
- Implement data debouncing (such as averaging N consecutive samples, threshold filtering);
- Cache the latest valid data to avoid reading the hardware too often (reducing bus load);
- Define a cache expiry time to keep the data current.
import time
class SHT30:
# New class attributes: debounce/cache configuration
DEBOUNCE_COUNT = 3 # Number of debounce samples
CACHE_EXPIRE = 500 # Cache expiry time (ms)
def __init__(self, i2c, addr=0x44, int_pin: int = None):
# Cache-related attributes
self._cache_temp = None
self._cache_hum = None
self._cache_update_time = 0 # Cache update time (ms)
# Other initialisation logic...
def read_temp_hum(self, debounce: bool = True):
"""Public method: read temperature and humidity (supports debouncing)"""
if not self._is_init:
raise SensorError("Sensor not initialised")
# Prefer the cache (if not expired)
current_time = time.ticks_ms()
if (self._cache_temp is not None and
time.ticks_diff(current_time, self._cache_update_time) < self.CACHE_EXPIRE):
self._log(3, "Using cached data")
return self._cache_temp, self._cache_hum
# Debounced sampling: read N times in a row and average
if debounce:
self._log(3, f"Debounce: sample {self.DEBOUNCE_COUNT} times")
temp_list = []
hum_list = []
for _ in range(self.DEBOUNCE_COUNT):
raw_data = self._read_raw_data()
temp, hum = self._parse_raw_data(raw_data)
temp_list.append(temp)
hum_list.append(hum)
time.sleep_ms(10) # Sample at 10ms intervals
temp = sum(temp_list) / len(temp_list)
hum = sum(hum_list) / len(hum_list)
else:
raw_data = self._read_raw_data()
temp, hum = self._parse_raw_data(raw_data)
# Validate and update the cache
self._validate_data(temp, hum)
self._cache_temp = temp
self._cache_hum = hum
self._cache_update_time = current_time
return temp, hum
# -------------------------- Usage example --------------------------
sht30 = SHT30(i2c, addr=0x44)
sht30.init()
# Read with debouncing (default)
temp, hum = sht30.read_temp_hum()
# Disable debouncing (fast read)
temp_fast, hum_fast = sht30.read_temp_hum(debounce=False)8.11 Type annotations and docstrings: standardised readability
MicroPython 1.19+ supports basic type annotations. The driver must:
- Add clear type annotations to all methods / parameters (improves readability and IDE support);
- Write complete docstrings (Google style), including parameters, return values, exceptions and examples;
- Add docstrings to key private methods as well, to ease maintenance.
class SHT30:
def read_temp_hum(self, debounce: bool = True) -> tuple[float, float]:
"""
Read temperature and humidity values (supports debouncing and caching)
Args:
debounce: whether to enable debouncing (default True); when enabled, 3 consecutive samples are averaged
Returns:
tuple[float, float]: temperature (℃), humidity (%RH)
Raises:
SensorError: sensor not initialised
SensorCommunicationError: I2C communication failed
SensorDataError: data check failed or value outside the valid range
Example:
>>> sht30 = SHT30(i2c)
>>> sht30.init()
>>> temp, hum = sht30.read_temp_hum()
>>> print(f"Temperature: {temp:.2f}°C, Humidity: {hum:.2f}%")
"""
# Method logic...
def _parse_raw_data(self, raw_data: bytes) -> tuple[float, float]:
"""
Private method: parse 6 bytes of raw data into temperature and humidity values
Args:
raw_data: 6 bytes of raw data read from the sensor (format: temp high 8 bits, temp low 8 bits, temp CRC, hum high 8 bits, hum low 8 bits, hum CRC)
Returns:
tuple[float, float]: the parsed temperature and humidity values
Raises:
SensorDataError: CRC check failed
"""
# Method logic...8.12 Singleton pattern: avoid initialising hardware more than once
If the same sensor (such as the only SHT30 at I2C address 0x44) is initialised multiple times, hardware conflicts easily result (such as binding the interrupt twice, or a timer left occupied). You must:
- Implement the singleton pattern so that a sensor instance is initialised only once;
- Provide a static
get_instance()method to obtain the unique instance; - Forbid creating multiple instances directly via
init.
class SHT30:
_instance = None # Singleton instance
_initialized = False # Initialisation flag
@staticmethod
def get_instance(i2c=None, addr=0x44, int_pin: int = None):
"""Static method: get the unique sensor instance"""
if SHT30._instance is None:
SHT30._instance = SHT30(i2c, addr, int_pin)
return SHT30._instance
def __init__(self, i2c=None, addr=0x44, int_pin: int = None):
"""Private constructor (do not call directly; use get_instance)"""
if SHT30._initialized:
raise SensorError("SHT30 is already initialised, do not create another instance! Use get_instance()")
# Initialisation logic...
SHT30._initialized = True
# -------------------------- Usage example --------------------------
# First call gets the instance (initialises)
sht30_1 = SHT30.get_instance(i2c, addr=0x44)
# Second call gets the instance (reuses the existing instance)
sht30_2 = SHT30.get_instance()
print(sht30_1 is sht30_2) # Prints True (same instance)
# Direct initialisation forbidden: sht30_3 = SHT30(i2c) # Raises an exception9. Requirements for the test file main.py
9.1 Core design principles
As the core vehicle for verifying the driver library's functionality, the test file must follow the core principles of "full coverage, flexible debugging, safe and controllable":
- Full coverage: cover all of the driver library's APIs as completely as possible (including queries, configuration, status reads, parameter settings, mode switching, etc.), ensuring every interface is usable and correct;
- Flexible debugging: for functions with high data update rates (such as real-time waveforms, high-frequency status reports) and mode-switching functions, the default automatic execution can be commented out, keeping only the function definition, so users can call them manually for debugging in the REPL (avoiding screen-flooding output and frequent hardware mode switches during automatic execution);
- Safe and controllable: through standardised initialisation, exception catching and resource clean-up logic, keep the hardware running safely during testing, with no resource leaks, hardware lock-ups or corrupted parameters in exception scenarios.
Of these, the most important is really full coverage:
Full coverage starts with a common API classification that works across chip types. Whether it is a sensor, motor driver, communication module or memory chip, break the interfaces down by "core functional dimension" so that no dimension is missed:
| Chip type | Core API functional dimensions | Typical API examples (key interfaces covering each dimension) |
|---|---|---|
| Sensors (temperature/humidity / radar / accelerometer) | 1. Basic status queries2. Core data acquisition3. Parameter configuration4. Mode switching5. Calibration and compensation | 1. Query device model / firmware version (SHT30/R60ABD1)2. Read temperature/humidity / heart rate / acceleration (SHT30/MPU6050)3. Set sampling rate / threshold / sensitivity (R60ABD1/BH1750)4. Switch between sleep / wake / monitoring modes (SHT30/R60ABD1)5. Zero calibration / error compensation (ADXL345/ADS1115) |
| Motor drivers (PCA9685/DRV8833) | 1. Hardware initialisation2. Motion control3. Status reads4. Reset / sleep | 1. Configure PWM frequency / channels (PCA9685)2. Adjust speed / direction / steps (DRV8833 / stepper motor drivers)3. Read current / fault status (DRV8833)4. Channel reset / chip sleep (PCA9685) |
| Communication modules (ESP8266/SIM800C) | 1. Network / protocol configuration2. Data transmit/receive3. Status queries4. Power control | 1. Configure AP connection / baud rate / band (ESP8266/SX1278)2. Transparent data transfer / send AT commands (SIM800C/NRF24L01)3. Query signal strength / connection status (SIM800C/ESP8266)4. Sleep / wake / power adjustment (SX1278/HC-05) |
| Memory chips (AT24C02/W25Q64) | 1. Data read/write2. Address configuration3. Erase / reset | 1. Single-byte / multi-byte read/write (AT24C02)2. Configure page address / sector address (W25Q64)3. Sector erase / chip reset (W25Q64) |
| GPIO / bus expanders (MCP23017/PCF8574) | 1. Pin configuration2. Level read/write3. Interrupt configuration | 1. Set pin input / output mode (MCP23017)2. Read / write pin levels (PCF8574)3. Configure interrupt trigger mode / callback (MCP23017) |
Full coverage is not just "calling every API". It means covering every calling scenario of each API according to the hardware characteristics of each chip, including normal parameters, boundary parameters and abnormal parameters:
| Test scenario type | Core verification goal | Scenario examples for different chips |
|---|---|---|
| Normal parameters | Verify basic usability of the API with default / common parameters | 1. Sensors: read temperature/humidity from SHT30 at the default sampling rate (1000ms), configure R60ABD1's default breathing threshold (15bpm)2. Motor drivers: control a DC motor with PCA9685 at 50Hz PWM3. Communication modules: connect ESP8266 to WiFi at the default baud rate (115200)4. Memory chips: write a single byte to AT24C02 at the default address (0x00) |
| Boundary parameters | Verify the API handles the hardware's limit parameters | 1. Sensors: BH1750 minimum (0.5Hz) / maximum (60Hz) sampling rate, ADS1115 ±2.048V/±6.144V limit ranges2. Motor drivers: PCA9685 lowest (20Hz) / highest (1000Hz) PWM frequency3. Communication modules: SX1278 minimum (125kHz) / maximum (1MHz) bandwidth4. Memory chips: erase W25Q64 at the maximum sector address (0x1FFF) |
| Abnormal parameters / environment | Verify the API's fault tolerance and error reporting | 1. Sensors: set R60ABD1 struggle sensitivity out of range (4, valid 0-2), pass an invalid I2C address (0x46) to SHT302. Motor drivers: pass a negative speed to DRV8833, configure a non-standard PWM frequency (1Hz) on PCA96853. Communication modules: connect ESP8266 to a WiFi name that does not exist, NRF24L01 address conflict4. Memory chips: write data to AT24C02 beyond the address range (0xFFF), read an unerased sector of W25Q64 |
Full coverage: keep the calling code for every API, supporting both manual and automatic verification:
| API characteristic | How the code is handled | Examples for different chips |
|---|---|---|
| Low-frequency core APIs | Keep automatic execution, called periodically in the main loop | 1. Sensors: read SHT30 temperature/humidity every 2 seconds, query R60ABD1 human presence status every 2 seconds2. Motor drivers: read PCA9685 channel duty cycle every 5 seconds3. Communication modules: query ESP8266 WiFi connection status every 10 seconds4. Memory chips: read data at a given AT24C02 address every 30 seconds |
| High-frequency update APIs | Keep the function definition, comment out automatic execution, call manually from the REPL | 1. Sensors: MPU6050 real-time gyroscope waveform printing (print_gyro_waveform ()), HC-SR04 continuous distance sampling (read_distance_continuous ())2. Motor drivers: real-time stepper speed feedback printing (print_stepper_speed ())3. Communication modules: NRF24L01 real-time transparent data printing (print_rf_data ()) |
| Mode-switching APIs | Keep the calling code, comment out automatic execution, trigger manually from the REPL | 1. Sensors: SHT30 sleep / wake (sleep ()/wakeup ()), R60ABD1 enable / disable sleep monitoring (enable/disable_sleep_monitor ())2. Communication modules: HC-05 master / slave mode switch (set_master_mode ()), SX1278 sleep / receive mode switch3. Motor drivers: DRV8833 brake / run mode switch (brake ()/run ()) |
| Batch-operation APIs | Wrap into batch test functions that can be called with one command from the REPL | 1. Sensors: R60ABD1 full parameter query (print_all_sensor_data ()), ADXL345 all-axis calibration (calibrate_all_axes ())2. Motor drivers: PCA9685 reset all channels (reset_all_channels ()), DRV8833 forward/reverse test of all motors (test_all_motors ())3. GPIO expanders: MCP23017 level read/write test of all pins (test_all_gpio_pins ())4. Memory chips: W25Q64 read-back verification of all sectors (read_all_sectors ()) |
9.2 Initialisation configuration section
After power-up, the hardware needs to finish its internal initialisation. The initialisation configuration section, before hardware objects are created, must therefore include a 3-second power-up delay and a debug print statement in a fixed format:
- The power-up delay ensures the hardware has completed its self-test and avoids initialisation timing problems;
- The debug print states which hardware / driver module is in use, making it quick to identify what is being tested.
# ======================================== Initialisation configuration ==========================================
# 3s power-up delay (mandatory, must not be removed)
time.sleep(3)
# Print debug message (uniform format: FreakStudio: Using + hardware/driver name + function description)
print("FreakStudio: Using R60ABD1 millimeter wave information collection")
# Subsequent hardware object initialisation (e.g. UART, driver class instance)
uart = UART(0, baudrate=115200, tx=Pin(16), rx=Pin(17), timeout=0)
processor = DataFlowProcessor(uart)
device = R60ABD1(processor, parse_interval=200)9.3 Standard metadata comment at the top of the file
The top of the file must contain a standardised metadata comment that states the runtime environment, author, function description and other key information, to support team collaboration and version management. Required fields:
| Comment field | Description | Example |
|---|---|---|
| Python env | MicroPython version it runs on | MicroPython v1.23.0 |
| Encoding declaration | Always UTF-8 | # -- coding: utf-8 -- |
| @Time | File creation / update time | 2025/11/4 5:33 PM |
| @Author | Author information | Li Qingshui |
| @File | File name | main.py |
| @Description | Description of the file's function (Chinese or English) | Code to test the R60ABD1 radar device driver class |
# Python env : MicroPython v1.23.0
# -*- coding: utf-8 -*-
# @Time : 2025/11/4 5:33 PM
# @Author : Li Qingshui
# @File : main.py
# @Description : Code to test the R60ABD1 radar device driver class
# @License : CC BY-NC 4.09.4 Fixed order and meaning of comment blocks
The file content must strictly follow the comment block order and meaning below. Each block is marked with a uniform separator (# ======================================== Block name =========================================) so the code structure is clear and easy to read:
- Import modules: holds only the
importstatements for hardware / functional dependencies (such asmachine,time, custom driver classes); - Global variables: holds global variables used across functions / the main program (such as sampling interval, last print time);
- Functions: holds the functions used for testing (such as data printing, active queries, mode configuration). Applying the core principle: calls to high-frequency update / mode-switching functions can be commented out;
- Custom classes: if the test file needs to define temporary helper classes, put them all here;
- Initialisation configuration: hardware object creation, parameter initialisation, driver initialisation, etc. (including the power-up delay and debug print from 9.1);
- Main program: the core execution logic (loop / task scheduling), including exception handling and resource clean-up.
# ======================================== Import modules =========================================
from machine import UART, Pin, Timer
import time
from data_flow_processor import DataFlowProcessor
from r60abd1 import R60ABD1, format_time
# ======================================== Global variables ============================================
last_print_time = time.ticks_ms()
print_interval = 2000
# ======================================== Functions ============================================
def print_report_sensor_data():
"""Print high-frequency reported sensor data (changes fast; call commented out by default)"""
... # Function definition kept; call commented out in the main program
# ======================================== Custom classes ============================================
# (No custom classes in this example; this block can be left empty or commented)
# ======================================== Initialisation configuration ==========================================
time.sleep(3)
print("FreakStudio: Using R60ABD1 millimeter wave information collection")
uart = UART(0, baudrate=115200, tx=Pin(16), rx=Pin(17), timeout=0)
...
# ======================================== Main program ===========================================
try:
while True:
...
# print_report_sensor_data() # High-frequency print function; default execution commented out, call manually from the REPL
...
except KeyboardInterrupt:
...
finally:
...9.5 Exception handling and safe shutdown
During testing, user interrupts, hardware communication errors and similar scenarios must be caught, using try/except/finally to ensure that:
- Common exceptions (KeyboardInterrupt, OSError, Exception) are caught and a friendly message is printed;
- The finally block always performs resource clean-up (closing the driver instance, releasing the serial port / timer, destroying objects), avoiding hardware faults.
# ======================================== Main program ===========================================
try:
while True:
# Core business logic
current_time = time.ticks_ms()
if time.ticks_diff(current_time, last_print_time) >= print_interval:
# Low-frequency query functions keep automatic execution; high-frequency functions are commented out
success, presence_status = device.query_presence_status()
if success:
print("Presence Status: %s" % ("Someone" if presence_status == 1 else "No one"))
else:
print("Query Presence Status failed")
last_print_time = current_time
time.sleep(0.2)
time.sleep_ms(10)
except KeyboardInterrupt:
# Catch user interrupt (Ctrl+C)
print("%s Program interrupted by user" % format_time())
except OSError as e:
# Catch hardware communication errors
print("%s Hardware communication error: %s" % (format_time(), str(e)))
except Exception as e:
# Catch other unknown exceptions
print("%s Unknown error: %s" % (format_time(), str(e)))
finally:
# Always perform resource clean-up, whether or not an exception occurred (core safety rule)
print("%s Cleaning up resources..." % format_time())
# 1. Call the driver class's close method to release internal resources (stop timers, close the serial port, etc.)
device.close()
# 2. Destroy hardware objects
del device
del uart
# 3. Print exit message
print("%s Program exited" % format_time())
10. Writing README.md
10.1 Basic requirements
- Project title
- Format:
# [Sensor/peripheral name] MicroPython Driver - States the project's purpose and target hardware directly.
- Format:
- Description
- Briefly introduce what the driver does, its main functions and where it applies.
- Readers should see at a glance "what this is, what it can do, and where it fits".
- Features
- List the highlights of what the driver implements, for example:
- Supported core functions (such as PWM setting, multi-channel control)
- Special functions (such as low-power mode, hardware reset)
- A concise API, etc.
- List the highlights of what the driver implements, for example:
- Hardware Requirements
- Test hardware table: controller board model, sensor model, communication interface type
- Wiring example: state which GPIO maps to SDA/SCL or other interface signals
- Software Environment
- Firmware version, driver version, dependent libraries (such as machine.I2C)
- File Structure
- A file tree, so users can quickly find the driver file, test file, documentation, etc.
- File Description
- Explain the purpose of each file, for example:
[driver file].py: core drivermain.py: test exampleREADME.md: documentation
- Explain the purpose of each file, for example:
- Design Idea
- Briefly describe how the driver is implemented or structured (optional)
- Quick Start
- Describe the usage steps one by one:
- Copy the driver file
- Wire it up
- Run the test program (with a code example)
- Describe the usage steps one by one:
- Notes
- For example chip operating conditions, usage limits, compatibility notes
- Version History
- A table recording version number, date, author and description of changes
- Contact
- Email or other contact details
- License
- State the open-source licence used (here CC BY-NC 4.0)
- Clearly distinguish the official MicroPython modules (MIT licence) from the driver you wrote (CC BY-NC 4.0)
10.2 Example template
# RCWL9623 Integrated Transceiver Ultrasonic Module Driver - MicroPython Version
## Contents
- [Introduction](#introduction)
- [Main features](#main-features)
- [Hardware requirements](#hardware-requirements)
- [File description](#file-description)
- [Core software design ideas](#core-software-design-ideas)
- [Usage](#usage)
- [Example program](#example-program)
- [Notes](#notes)
- [Contact](#contact)
- [License](#license)
---
## Introduction
The ultrasonic ranging module based on the RCWL9623 chip is a high-performance ranging device with integrated transmit and receive, supporting multiple communication modes (GPIO, 1-Wire, UART, I2C). The module measures the distance to an object from the travel time of ultrasound, and features fast response, accurate ranging and strong interference resistance. It is widely used in robot obstacle avoidance, smart home ranging, safety monitoring and similar scenarios.
> **Note**: Not suitable for high-precision use cases, such as safety and life-saving applications.
This project provides MicroPython-based driver code and example programs so developers can quickly integrate the RCWL9623 module and implement distance measurement.
---
## Main features
- **Multiple operating modes**:
- GPIO trigger/Echo
- Single-wire (1-Wire)
- UART serial communication
- I2C bus communication
- **Ranging range**: about 20cm to 7m; out-of-range readings return invalid
- **Uniform units**: distance is calculated from acoustic time of flight, always in centimetres (cm)
- **Simple to use**: a unified interface `read_distance()` for quick integration
- **Cross-platform**: compatible with multiple hardware platforms (Raspberry Pi Pico and other MicroPython-compatible boards)
---
## Hardware requirements
### Recommended test hardware
- Raspberry Pi Pico/Pico W
- RCWL9623 ultrasonic module
- Several Dupont wires
### Module pin description
| RCWL9623 pin | Function |
|--------------|----------|
| VCC | Power positive (3.3V-5V) |
| GND | Power negative |
| TRIG | Trigger pin (GPIO mode) |
| ECHO | Echo pin (GPIO mode) |
| IO | Single-wire data pin |
| RX/TX | UART communication pins |
| SCL/SDA | I2C communication pins |
---
## File description
### rcwl9623.py
Implements the four operating modes of the RCWL9623 module
==========
HSA Agents
==========
*******
Agent 1
*******
Name: driver; the core class `RCWL9623` provides a unified interface.
#### Class definition
```python
class RCWL9623:
"""
This class provides control of the RCWL9623 ultrasonic ranging module, supporting four operating modes: GPIO/OneWire/UART/I2C.
Note that the effective measuring distance of this ultrasonic chip is 25CM to 700CM; out-of-range readings return None.
Attributes:
mode (int): current operating mode, one of the class constants:
GPIO_MODE, ONEWIRE_MODE, UART_MODE, I2C_MODE.
trig (Pin): trigger pin object in GPIO mode (valid only in GPIO mode).
echo (Pin): echo pin object in GPIO mode (valid only in GPIO mode).
pin (Pin): data pin object in OneWire mode (valid only in OneWire mode).
uart (UART): serial port instance in UART mode (valid only in UART mode).
i2c (I2C): I2C instance in I2C mode (valid only in I2C mode).
addr (int): I2C device address (valid only in I2C mode).
Methods:
__init__(mode, *, gpio_pins=None, onewire_pin=None, uart=None, i2c=None, addr=None):
Initialise the ultrasonic module and configure the interface for the selected mode.
read_distance() -> float | None:
Read the distance (in centimetres); returns None on failure.
_read_gpio() -> float | None:
Ranging implementation for GPIO mode (internal method).
_read_onewire() -> float | None:
Ranging implementation for OneWire mode (internal method).
_read_uart(max_retries=5) -> float | None:
Ranging implementation for UART mode (internal method).
_read_i2c() -> float | None:
Ranging implementation for I2C mode (internal method).
==========================================
This class provides control for the RCWL9623 ultrasonic distance sensor,
supporting four operating modes: GPIO, OneWire, UART, and I2C.
Note that the effective measurement distance of this ultrasonic chip is 25CM to 700CM,
and the distance will return None if it exceeds the range.
Attributes:
mode (int): Current operating mode, one of the class constants:
GPIO_MODE, ONEWIRE_MODE, UART_MODE, I2C_MODE.
trig (Pin): Trigger pin object in GPIO mode (valid only in GPIO mode).
echo (Pin): Echo pin object in GPIO mode (valid only in GPIO mode).
pin (Pin): Data pin object in OneWire mode (valid only in OneWire mode).
uart (UART): UART instance in UART mode (valid only in UART mode).
i2c (I2C): I2C instance in I2C mode (valid only in I2C mode).
addr (int): I2C device address (valid only in I2C mode).
Methods:
__init__(mode, *, gpio_pins=None, onewire_pin=None, uart=None, i2c=None, addr=None):
Initialize the ultrasonic module with the specified interface configuration.
read_distance() -> float | None:
Read distance in centimeters, returns None on failure.
_read_gpio() -> float | None:
Distance measurement implementation for GPIO mode (internal method).
_read_onewire() -> float | None:
Distance measurement implementation for OneWire mode (internal method).
_read_uart(max_retries=5) -> float | None:
Distance measurement implementation for UART mode (internal method).
_read_i2c() -> float | None:
Distance measurement implementation for I2C mode (internal method).
"""
# Operating mode constants
GPIO_MODE, ONEWIRE_MODE, UART_MODE, I2C_MODE = [0, 1, 2, 3]
# Fixed I2C communication address
I2C_DEFAULT_ADDR = const(0x57)
# Keyword arguments are used: the driver only uses bus/serial port instances and does not create/configure them. Hardware initialisation (pin selection, baud rate, frequency) is managed centrally by the application layer, which makes the driver lighter and more reusable and reduces code tied to hardware platform differences;
# also, in real embedded systems the I2C bus is often shared by several devices, so requiring an instance to be passed in avoids the driver initialising it again and lets bus resources be managed centrally at the outer level;
# and named parameters such as gpio_pins, onewire_pin, uart, i2c are more intuitive than a pile of positional or mixed parameters, reducing the chance of calling errors (especially in a multi-mode class).
def __init__(self, mode: int, *, gpio_pins=None, onewire_pin=None, uart=None, i2c=None, addr=None):
```
### main.py
Example main program: initialises the sensor according to the selected operating mode and reads the distance in a loop.
## Core software design ideas
## Core software design ideas
### Modular design
- The reading logic for each communication mode is encapsulated in its own method
- Called through the unified interface `read_distance()`
- Supports flexible extension with new functions (e.g. adding new sensor types or communication modes)
### Time-of-flight ranging principle
- **GPIO mode**: send a pulse on the `Trig` pin and time the high-level width on the `Echo` pin to calculate the distance
- **Formula**: distance = (high-level time × speed of sound) / 2, with the speed of sound taken as 340 m/s (about 0.034 cm/μs)
### Data validity checks
- Abnormal values are filtered out by a range check (2cm ~ 700cm)
- **UART/I2C modes**: a retry mechanism for data reads is provided
- Error handling logic keeps the system stable under abnormal conditions
### Cross-platform compatibility
- Depends only on the **MicroPython standard library**, reducing hardware coupling
- Provides a hardware abstraction layer (HAL) interface for easy porting to different hardware platforms
### Hardware abstraction layer design
- Separates low-level hardware control (GPIO, UART, I2C) from the ranging algorithm logic
- Hides hardware differences behind a unified interface
- Easier to maintain and extend later
### Clear interface documentation
- Provides function descriptions, parameter descriptions and return value descriptions
- Includes error code definitions and handling suggestions
## Usage
### Hardware wiring (Raspberry Pi Pico example)
| RCWL9623 pin | Pico GPIO pin |
|---------------|----------------|
| VCC | 3.3V or 5V |
| GND | GND |
| TRIG | GP5 |
| ECHO | GP4 |
> **Note:**
> - Make sure **VCC** and **GND** are wired correctly
> - `TRIG` is an output pin, `ECHO` is an input pin
> - Different modes (GPIO/UART/I2C) may use different pins; refer to the example program and modify accordingly
---
### Software dependencies
- **Firmware version**: MicroPython v1.19+
- **Built-in libraries**:
- `machine` (for GPIO, UART, I2C control)
- `time` (for delays and time measurement)
- **Development tools**: PyCharm or Thonny (recommended)
---
### Installation steps
1. Flash the **MicroPython firmware** to the Raspberry Pi Pico
2. Upload `rcwl9623.py` and `main.py` to the Pico
3. Modify the pin configuration in `main.py` to match your hardware connections
4. Run `main.py` in the development tool to start ranging
## Example program
```python
# Python env : MicroPython v1.23.0
# -*- coding: utf-8 -*-
# @Time : 2025/08/13 17:45
# @Author : Miao Guicheng
# @File : main.py
# @Description : RCWL9623 ultrasonic module test main program, tests the four modes GPIO/OneWire/UART/I2C
# ======================================== Import modules =========================================
# Import hardware modules
from machine import Pin, UART, I2C
# Import time-related modules
import time
# Import ultrasonic-related modules
from rcwl9623 import RCWL9623
# ======================================== Global variables ============================================
# I2C clock frequency (Hz), default 100kHz
I2C_DEFAULT_FREQ = 100_000
# Fixed I2C communication address
I2C_DEFAULT_ADDR = 0x57
# Test mode: options are RCWL9623.GPIO_MODE, RCWL9623.ONEWIRE_MODE, RCWL9623.UART_MODE, RCWL9623.I2C_MODE
test_mode = RCWL9623.ONEWIRE_MODE
# Test interval, in seconds
test_interval = 1
# ======================================== Functions =============================================
# ======================================== Custom classes =============================================
# ======================================== Initialisation configuration ===========================================
# 3s power-up delay
time.sleep(3)
# Print debug message
print("FreakStudio: Test RCWL9623 Module")
# Select pins / create the communication interface for the chosen mode, and instantiate the RCWL9623 object
if test_mode == RCWL9623.GPIO_MODE:
# GPIO pin tuple (trig_pin, echo_pin)
gpio_pins = (5, 4)
sensor = RCWL9623(mode=RCWL9623.GPIO_MODE, gpio_pins=gpio_pins)
print("FreakStudio: GPIO Mode")
elif test_mode == RCWL9623.ONEWIRE_MODE:
onewire_pin = 5
sensor = RCWL9623(mode=RCWL9623.ONEWIRE_MODE, onewire_pin=onewire_pin)
print("FreakStudio: OneWire Mode")
elif test_mode == RCWL9623.UART_MODE:
uart = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))
sensor = RCWL9623(mode=RCWL9623.UART_MODE, uart=uart)
print("FreakStudio: UART Mode")
elif test_mode == RCWL9623.I2C_MODE:
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=I2C_DEFAULT_FREQ)
sensor = RCWL9623(mode=RCWL9623.I2C_MODE, i2c=i2c)
print("FreakStudio: I2C Mode")
else:
raise ValueError("unknown mode: %s" % test_mode)
# ======================================== Main program ===============================================
# Ranging loop
print("FreakStudio: Start Test")
try:
while True:
# Measure distance
distance = sensor.read_distance()
# Check whether the ranging result is valid
# Note: the effective measuring distance of this ultrasonic chip is 25CM to 700CM; out-of-range readings return None.
if distance is not None:
# Print the ranging result
print("Get Distance: %.2f cm" % distance)
# Delay
time.sleep(test_interval)
except KeyboardInterrupt:
print("FreakStudio: Exit Test")
except Exception as e:
print("FreakStudio: Error: %s" % e)
```
## Notes
## Notes
### Ranging range limits
- Valid range is about **20cm ~ 7m**
- Data below 20cm or above 7m is treated as invalid
- The actual blind zone is about **25cm** (determined by the module's physical characteristics)
---
### Mode configuration requirements
| Mode | Notes |
|----------|----------|
| GPIO | `Trig` is output, `Echo` is input; avoid signal interference |
| OneWire | Make sure the single-wire timing is accurate |
| UART | Check the module's baud rate setting (default 9600) |
| I2C | Check the device address (default `0x57`) |
---
### Power requirements
- Supply voltage: **5V**
- Make sure the power supply is stable and avoid voltage fluctuations
- A separate supply is recommended for high-power applications
---
### Sampling frequency
- Keeping it at around **1 second** is recommended
- Avoid sampling too fast, which makes the data unstable
- Consider module heat dissipation for high-frequency measurement
---
### Environmental factors
- Avoid use in **high-temperature, high-humidity** environments
- **Strong wind** may affect ranging accuracy
- Smooth surfaces may cause **abnormal signal reflection**
## Contact
If you have any questions or need help, contact the developer via:
💻 **GitHub**: [https://github.com/yourusername](https://github.com/yourusername)
---
## License
In this project, except for official MicroPython modules such as `machine` (MIT licence), all driver and extension code written by the author is released under the **Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)** licence.
You are free to:
- **Share** — copy and redistribute the material in any medium or format
- **Adapt** — remix, transform, and build upon the material
Under the following terms:
- **Attribution** — You must give appropriate credit, provide a link to the licence, and indicate if changes were made (to the original work). You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
- **NonCommercial** — You may not use the material for commercial purposes.
- **Reasonable citation** — The source may be clearly credited in code comments, documentation, demo videos or project descriptions.
**Copyright belongs to FreakStudio.**
11. Licence requirements
11.1 Licence type
All driver and extension code in this project is released under the MIT licence.
11.2 Fixed format of the copyright notice
Name this file LICENSE directly. Note: no file extension at all!
MIT License
Copyright (c) 2025 Lee Qingshui / Freak
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.- Attribution: you must state "Copyright 20xx Lee Qingshui / Freak" in the code, documentation or demo, together with a link to the licence (20xx is the year).
- Non-commercial use: use of this code in any commercial project or profit-making activity is prohibited.
- Change notes: if you modify the code, you must state what was changed and when in the documentation or comments.
- Apart from official modules, all new code, extension code and example programs are subject to CC BY-NC 4.0.
12. Requirements for writing package.json
12.1 Template file
The following is a standard-compliant package.json template that can be used directly to configure a driver package:
{
"name": "sensor_driver",
"urls": [
["sensor.py", "code/sensor.py"]
],
"version": "1.0.0",
"_comments": {
"chips": "Chip models the package runs on; all means no chip restriction",
"fw": "Specific firmware the package depends on, e.g. ulab, lvgl; all means no firmware dependency"
},
"description": "A MicroPython library to control [Sensor name]",
"author": "Author Name",
"license": "MIT",
"chips": "all",
"fw": "all"
}12.2 Field descriptions
| Field | Type | Required | Description |
|---|---|---|---|
| name | String | ✅ | Package name, using lower-case letters + underscores, e.g. bmp280_driver; must match the folder name. |
| urls | 2D array | ✅ | File mapping rules; each entry is ["target file name", "source file path"]: - Target file name: the file name on the device (e.g. bmp280_float.py) - Source file path: path relative to the package root (e.g. code/bmp280_float.py) |
| version | String | ✅ | Semantic version number in the format major.minor.patch, e.g. 1.0.0. |
| _comments | Object | ❌ | Comment field, used only to explain the meaning of the chips and fw fields; does not affect parsing. |
| description | String | ❌ | Description of what the package does, to help developers understand the driver's purpose. |
| author | String | ❌ | Author information. When based on someone else's code, it must match the original author; for original code, fill in the team / individual name. |
| license | String | ❌ | Licence type. When based on someone else's code, follow the original repository's licence; original code uses MIT by default. |
| chips | String / array | ❌ | Supported chip models: - "all": no chip restriction - array: e.g. ["ESP32", "STM32F407"], specifying compatible chips |
| fw | String / array | ❌ | Required firmware components: - "all": no firmware dependency - array: e.g. ["ulab", "lvgl"], specifying required firmware |
12.3 Example file (using bmp280_driver)
{
"name": "bmp280_driver",
"urls": [
["bmp280_float.py", "code/bmp280_float.py"]
],
"version": "1.0.0",
"_comments": {
"chips": "Chip models the package runs on; all means no chip restriction",
"fw": "Specific firmware the package depends on, e.g. ulab, lvgl; all means no firmware dependency"
},
"description": "A MicroPython library to control BMP280 pressure sensor",
"author": "robert-hh",
"license": "MIT",
"chips": "all",
"fw": "all"
}Note: this driver is based on open-source code by robert-hh, so the author and license fields match the original repository.
12.4 Verifying the download
- Preparation: make sure the Raspberry Pi Pico has MicroPython firmware flashed and is connected to the computer over USB.
- Run the install command:
mpremote mip install github:FreakStudioCN/GraftSense-Drivers-MicroPython/sensors/bmp280_driver- Confirm the installation:
mpremote fs ls lib/If the output contains bmp280_float.py, the installation succeeded.
12.5 Notes on licences and copyright notices
Based on someone else's code:
- If the original repository contains a
LICENSEfile, copy the original licence text directly into the project'sLICENSEfile; theauthorandlicensefields inpackage.jsonmust match the original repository. - If the original repository has no licence, use the FreakStudio default licence (
MIT) and credit the source inREADME.md.
Original code: use the FreakStudio copyright notice and follow the MIT licence.
Version history
Version | Modified by | Date | Content |
v1.0 | Li Zisheng | 2025/08/13 | Initial document |
v1.1 | Miao Guicheng, Li Zisheng | 2025/08/17 | Added examples to explain the parts that beginners find hard to understand |
v1.2 | Chen Xu, Li Zisheng | 2025/08/30 | Added the folder structure |
v1.3 | Chen Xu | 2025/09/09 | Standardised comments, unified the examples in the document, unified methods (class member functions / plain functions / functions with exceptions) |
v1.4 | Li Zisheng | 2025/12/09 | Added Chapter 8, core design and implementation rules, and refined Chapter 9. |
v1.5 | Li Zisheng | 2026/02/12 | Added the package.json writing standard and changed the licence type. |