Contents
- Project Description
- 1. Introduction
- 2. Main Functions
- 3. Hardware Requirements
- 4. Software Environment
- 5. File Structure
- 6. Description of Key Documents
- 7. Core Idea of Software Design
- 8. Instructions for Use
- 9. Sample Program
- 10. Notes
- 11. Version Record
- 12. Contact the Developer
- 13. Licensing Agreement
- Appendix I: Project Source Code Download
- Appendix II: Hardware Module Reference Materials
- Version Record


Project Description
1. Introduction
1.1 Project Background
Traditional LED lamps mostly feature fixed brightness adjustment, and buzzers usually produce a single sound effect, lacking interactivity with the environment. Based on the GraftPort-RP2040 development board, this project integrates the RCWL9623 high-precision ranging sensor to realize "distance-sound and light" linkage control, addressing the insufficient interactivity of traditional audio-visual devices. Meanwhile, it incorporates the lightweight task scheduling and exception handling mechanism of MicroPython to ensure the stable operation of the system.
1.2 Overview of Main Functions of the Project
This project is developed based on MicroPython. Its core function is to detect the distance of the target in real time through the RCWL9623 ranging sensor, and dynamically control the brightness of PiranhaLED (the closer the distance, the higher the brightness) and the frequency of the passive buzzer (the closer the distance, the higher the frequency) after data filtering; it supports on-board key interrupt to switch task start and stop, has built-in automatic garbage collection (GC) to avoid memory leakage, is equipped with exception capture and rate-limited printing for convenient problem locating, and the sensor initialization retry mechanism improves hardware compatibility.
1.3 Applicable Scenarios or Application Area
- Smart Home: As an interactive ambient light, it will increase brightness and play high-frequency sound effects when someone approaches, and dim the brightness and switch to low-frequency sound effects when someone moves away;
- Interactive installation: An experiential device for science and technology museums and exhibition halls, which triggers changes in sound and light via distance sensing;
- Teaching Demo: For
MicroPythontask scheduling,I2Csensor communication, interrupt processing, data filtering and other knowledge points in practical teaching; - Small-sized toys: Interactive playthings for children that enhance fun by providing sound and light feedback controlled by distance.
2. Main Functions
- Real-time ranging and data filtering: The
RCWL9623sensor collects distance data (unit: cm) every 200ms. A mechanism of "three-point mean filtering + outlier rejection (difference ≤ 100cm)" is adopted to avoid instantaneous interference and ensure data stability; - Dynamic LED Brightness Control: Non-linear brightness mapping based on distance (brighter at close range, dimmer at long range) with configurable distance range (default: 25-100cm); exponential mapping (exponent = 5) is adopted to enhance the sensitivity of brightness variation;
- Buzzer frequency linkage: maps distance segments to preset musical notes (e. g.,
A5,G5etc. , high frequency for short distance, low frequency for long distance), automatically mutes when exceeding the maximum distance, and the note sequence supports dynamic generation and fallback configuration; - Key Interrupt Interaction: The onboard key triggers a falling-edge interrupt, which can toggle the core task between "run/pause"; when paused, the
LEDand buzzer will be turned off immediately, and the filtering buffer will be cleared to avoid data anomalies upon resumption; - Automatic memory management: Detects memory when idle, and automatically triggers
GCif memory usage is below the threshold (100000 bytes by default), preventingMicroPythonfrom crashing due to memory leaks; - Exception Fault Tolerance Mechanism: Sensor initialization supports multiple retries (configurable count), and upon failure, it triggers
LEDflashing + terminal error blocking; when an exception is thrown during task execution, the full stack trace will be printed with rate limiting (default: 1 time/second) to avoid screen flooding; - Flexible board-level adaptation: Based on
board.pyto decouple pin mapping, it supports subsequent expansion to otherRP2040development boards without modifying the core business logic.
3. Hardware Requirements
3.1 Hardware Required
The project is based on the GraftPort-RP2040 development board as the main controller:

Other required modules include:

- GtaftSense-RCWL9623 Transmit-Receive Integrated Ultrasonic Sensor Module (
I2Ccommunication, default address0x57, ranging range: 25-700cm); - GtaftSense - Piranha LED Light Module (single-channel
LED, common cathode, configured asPOLARITY_CATHODEin code); - GtaftSense - Passive Buzzer Module (requires frequency driving, does not support direct high/low level control);
- GraftSense-SY7656 Lithium Battery Charge-Discharge Module:(connects to polymer lithium battery, outputs 5V voltage, equipped with
Type-Ccharging port);
3.2 Hardware Connection
RCWL9623 Transmit-Receive Integrated Ultrasonic Sensor Module: Connect via PH2.0-4P cable to the I2C0 interface;

Piranha LED light module: connect to digital interface 0 via PH2.0-4P connection cable;

Passive Buzzer Module: Connect to Digital Port 1 via PH2.0-4P connection cable;

Lithium Battery Charge and Discharge Module: BAT interface is connected to the lithium battery, and the OUT interface supplies power to the main control board via a PH2.0-2P connection cable.



3.3 Hardware Connection
First, use M3 plastic pillars to fix each module and the main control board to the bottom plate of the housing (M3 screw holes are pre-drilled on both the main control board and the housing):


Next, secure the housing around its perimeter using M3 plastic pillars, then fasten M3 screws into the corresponding positions to complete the assembly:

3.4 Notes
When the main control board is not connected to an external watchdog module, the RUN DIP switch 2 must be turned on:

The lithium battery charge-discharge module supports power level display, and you can charge it via the following Type-C interface:

4. Software Environment
- Core Firmware:
MicroPython v1.23.0(adaptation required for GraftPort-RP2040, with support formachine.Pin/I2C/Timermodules and soft timer scheduling); - Development IDE:
PyCharm(used for code writing, uploading and debugging, supportsMicroPython REPLinteraction, and requires the installation of theMicroPythonplugin); - Auxiliary Tools:
Python 3.12+(optional, for running local helper scripts such as firmware flashing scripts);mpy-cross v1.23.0(used to. pyfiles compile into. mpyto reduce the memory usage of the development board, optional);mpremote v0.11.0+(replacesThonnyfor file upload, supports command-line operations, optional);
- Dependency Modules: No additional third-party libraries are required; all drivers (including but not limited to
passive_buzzer_driver.py) are custom-implemented and provided along with the project files.
5. File Structure
Project root directory/
├── libs/ # Common utility library folder, holds reusable core modules
│ └── scheduler/ # Task scheduler library, implements multi-task management based on soft timers (supports adding/pausing/resuming tasks, idle/exception callbacks)
├── drivers/ # Hardware driver folder, encapsulates control interfaces for different peripherals (high cohesion, exposes only necessary methods)
│ ├── passive_buzzer_driver/ # Passive buzzer driver package, provides the `play_tone(freq, duration)` method
│ ├── piranha_led_driver/ # PiranhaLED driver package, provides the `set_brightness(percent)` method
│ └── rcwl9623_driver/ # RCWL9623 driver package, provides the `read_distance()` method
├── tasks/ # Task logic folder, holds business-related task implementations (decoupled from hardware drivers)
│ ├── sensor_task.py # Core task module, defines the `SensorBuzzerLedTask` class, implements the complete "ranging → filtering → sound and light control" logic
│ └── maintenance.py # Maintenance task module, provides `task_idle_callback` (automatic GC) and `task_err_callback` (exception handling)
├── main.py # Project entry file, responsible for hardware initialization, task creation, scheduler startup, and exception blocking handling
├── board.py # Board support file, defines the pin mapping of the GraftPort-RP2040 (fixed pins, I2C/DIO/ADC interfaces)
├── conf.py # Configuration file, holds customizable parameters (such as sensor initialization retry count, GC threshold, etc.)
├── README.md # Project documentation, includes feature introduction, usage steps, notes, etc.
├── build/ # Build artifacts / scripts / firmware packaging specifications (placeholder)
├── tools/ # Development / testing / packaging helper scripts
└── docs/ # Documentation: design notes, API specifications, development board pin mapping and related images
├── graftport_pinout_table.md # GraftPort-RP2040 pin mapping table
├── xxx.jpg # Several photos related to development board \m module \ wiring
└── examples # A folder of some running examples; this project has none.If you want to add other sensor modules to the main control board, it is recommended that you refer to the docs folder, and check the graftport_pinout_table.md file for the pin mapping.
6. Description of Key Documents
main.py: the project entry point, whose core logic includes:- Power on and delay for 3 seconds (wait for the hardware to stabilize), then initialize the onboard
LED, extendedLED, buzzer, and buttons (including interrupt registration); - Initialize
I2C0and theRCWL9623sensor (multiple retries are supported; upon failure,fatal_hangwill be called to block the system and report errors via flashing indicator lights); - Create
SensorBuzzerLedTaskinstance (pass in hardware driver and configuration parameters), and encapsulate it as a scheduler task with a period of 200ms; - Initialize
Scheduler(software timer with a scheduling period of 50ms), add tasks and start scheduling, then enter an infinite loop; - Define
button_handlerinterrupt callback (for toggling task start/stop),fatal_hangblocking function (for critical error handling).
- Power on and delay for 3 seconds (wait for the hardware to stabilize), then initialize the onboard
tasks/sensor_task.py: Core business task,key logic of the SensorBuzzerLedTaskclass:__init__: Initialize the hardware instance, the filtering buffer (adequewith a capacity of 3), and the musical note mapping table (which matches musical notes by segments based on distance);tick: Executed every 200ms, the process is "read raw distance → outlier filtering → three-point mean filtering → calculate LED duty cycle → match buzzer frequency → control hardware";_compute_led_duty: Implements a non-linear mapping from distance to LED brightness (with an exponent of 5) to prevent excessively gradual brightness changes;_choose_note: Match musical notes based on the filtered distance, and return "OFF"(mute) when out of range;immediate_off: Immediately turn off the LED and buzzer, clear the buffer, and this function is for invocation when the key is paused.
tasks/maintenance.py: System maintenance module, key functions:task_idle_callback: Triggered when the scheduler is idle; if it detects that the memory usage is lower thanGC_THRESHOLD_BYTES(100000 bytes by default), it will executegc.collect ();task_err_callback: Triggered when an exception is thrown by a task, prints the full traceback (preferentially usessys.print_exception), then delays forERROR_REPEAT_DELAY_S(1 second by default) to prevent screen flooding;- Supports reading configurations from
conf.py, and uses default values when no configuration is provided to ensure compatibility.
drivers/xxx_driver: hardware driver module, all adopting the "instantiation + method call" pattern, only exposing hardware-related control interfaces while shielding underlying details:passive_buzzer_driver.py:The Buzzerclass outputs PWM signals viathe Pin, and itsplay_tonemethod controls the frequency and playback duration;piranha_led_driver.py:The PiranhaLEDclass controls brightness via PWM, andset_brightnessaccepts a percentage parameter ranging from 0 to 100%;rcwl9623_driver.py:The RCWL9623class reads sensor registers via I2C, and theread_distancemethod returns the ranging value (in cm) or None (on failure).
board.py: a board-level pin mapping module that defines theBOARDSdictionary (including the fixed pins of GraftPort-RP2040 and the mapping ofI2C/DIO/ADCinterfaces), provides interfaces such asget_fixed_pinandget_i2c_pinsto realize the decoupling of board-level configuration and business logic; to expand for other development boards later, you only need to add sub-items toBOARDS.conf.py: User configuration file. The parameters that need to be manually defined by the user include:I2C_INIT_MAX_ATTEMPTS(number of retries for sensor initialization),I2C_INIT_RETRY_DELAY_S(retry interval in seconds),ENABLE_DEBUG(debug print switch),AUTO_START(whether the task starts automatically). If not defined, the system will use the default values.
7. Core Idea of Software Design

- System layering concept: A "four-tier architecture" is adopted to achieve decoupling and reuse
- Hardware Driver Layer (
drivers/): It is only responsible for the low-level control of hardware and contains no business logic. For example, a buzzer driver only concerns itself with "how to play a specified frequency" rather than "when to play it"; - Task Logic Layer (
tasks/): Implements business logic based on the interfaces provided by the driver layer. For example,SensorBuzzerLedTaskonly calls the driver'sset_brightnessmethod and does not care about the pin number of theLED; - Scheduling Control Layer (
libs/scheduler.py): Provides generic task management capabilities, supporting task addition/pause/resume, idle/exception callbacks, and is independent of specific business logic; - Entry Layer (
main.py): responsible for "assembling" all layers, following the sequence of initializing hardware → creating tasks → starting scheduling; it acts as the "glue" of the system and contains no core business logic.
- Hardware Driver Layer (
- Principles of Module Division: high cohesion, low coupling, and ease of maintenance and expansion
- High Cohesion: each module is only responsible for the Single Responsibility Principle, for example,
maintenance.pyonly handles system maintenance (GC, exceptions) and does not involve acousto-optic control; - Low coupling: Modules interact through "interfaces" instead of directly manipulating internal variables. For example,
SensorBuzzerLedTaskobtains data viarcwl.read_distance ()without directly accessing theRCWL9623'sI2Cregisters. - Scalability: When adding new hardware (e. g., temperature sensors), simply add the corresponding driver under
drivers/and create a new task undertasks/without modifying existing code; when expanding the development board, just add the pin mapping inboard.py, which will not affect the business logic.
- High Cohesion: each module is only responsible for the Single Responsibility Principle, for example,
- Core Mechanism: Ensuring System Stability and User Experience
- Task scheduling mechanism: Implemented based on a soft timer (
Timer (-1)), with a scheduling cycle of 50ms and a core task cycle of 200ms; it judges whether a task is due for execution via "counter accumulation" to avoid timer nesting conflicts. - Data Filtering Mechanism: It adopts the "outlier elimination + three-point mean filtering" method, which not only filters out instantaneous jumps (such as sensor misreading) but also ensures real-time data performance, avoiding the lag problem of pure mean filtering;
- Interactive Feedback Mechanism: Key interrupt callbacks take "immediate effect": the sound and light output will be turned off immediately when paused, so as to avoid no response after user operations; when sensor initialization fails, it will "report errors explicitly"(flashing indicator + terminal message), which facilitates troubleshooting of hardware connection issues;
- Fault-tolerant mechanism: All critical operations (such as hardware control, memory reading) are wrapped in
try-exceptblocks to prevent a single module failure from crashing the entire system; for example,LEDcontrol failure will not affect the normal operation of the buzzer.
- Task scheduling mechanism: Implemented based on a soft timer (
- Task Execution Process: The task execution process is as follows:

8. Instructions for Use
8.1 Hardware Connection
Connect the main control board, each sensor module and the battery according to the connection method specified in the "hardware requirements";
8.2 Run the Project (Using PyCharm + MicroPython Plugin)
Open PyCharm and install the corresponding MicroPython plugin.

In the plugin, select Target Device (Target Device) as RP2040, and enable Auto-detect device path (Auto-detect device path).

Set Project/firmware as the project root directory.

Modify the runtime configuration:

- Check Allow multiple instances (
Allow multiple instances) - Select Store as Project File (
Store as project file) - Click OK to save the configuration.
Click the IDE green triangle button in the upper right corner to run, and you can start uploading the firmware and executing the project.

8.3 Modification of Running Configuration
You can configure conf.py to modify or add parameters as needed, for example:
# conf.py example configuration
I2C_INIT_MAX_ATTEMPTS = 3 # Maximum number of sensor initialization retries
I2C_INIT_RETRY_DELAY_S = 0.5 # Interval between retries (seconds)
ENABLE_DEBUG = True # Whether to enable debug printing
AUTO_START = True # Whether to run tasks automatically at startup8.4 Functional Testing
Turn on the VBAT battery power switch located below the main control board, and you will see the power indicators on the main control board and the module light up:

- Distance measurement control: Bring a hand or an object close to
RCWL9623(within the range of 25-100cm), and check whether the brightness of theLEDincreases as the distance decreases, and whether the frequency of the buzzer rises as the distance decreases; - Button Switching: Press the onboard button to pause the task (
LEDturns off, buzzer mutes); press it again to resume the task (sound and light change with distance); - Exception test: Disconnect
RCWL9623'sI2Cline, the program will enterfatal_hang, the onboardLEDflashes in a cycle of two short blinks, and the terminal prints an initialization failure message.
When conf.py remains unchanged in configuration and there is no issue with the hardware connection, the program can run normally (the buzzer's tone changes as the distance between the hand and the device varies):

The terminal output is as follows:

8.5 Debugging and Problem Localization
- If the function is abnormal, ensure that
ENABLE_DEBUG = True, then check the debug information in the terminal (e. g."raw: 30 filt: 32 led duty: 85 buzzer: 880 A5") to determine whether the data is normal; - If the sensor initialization fails, check
I2Cpin connections, sensor address (default0x57), and retry count configuration. - The ultrasonic sensor module has a small field of view. Please ensure that the hand/object moves as close to the normal line of the ultrasonic probe as possible.
9. Sample Program
There are no other reference sample codes for this project, you can directly firmware make modifications in the folder.
10. Notes
- Sensor-related:
RCWL9623has a ranging range of 25-700cm, and will returnNoneor an abnormal value when out of range. Clipping has been implemented in the code (default: 25-100cm); if you need to adjust the range, modify theSensorBuzzerLedTaskparametersmin_distandmax_dist;RCWL9623defaultI2Caddress is0x57. If an address conflict occurs, you need to modify the sensor hardware jumper (if supported) or theI2C0_RCWL9623_ADDRvariable in the code;- The recommended number of sensor initialization retries is ≥3 (
I2C_INIT_MAX_ATTEMPTS ≥ 3) to prevent initialization failure caused by unstableI2Ccommunication at the moment of power-on.
- Hardware Connection Related:
- Common cathode
LEDrequires that when initializing thePiranha LED, thepolarityparameter be set toPOLARITY_CATHODE, and for common anode, set it toPOLARITY_ANODE; incorrect polarity will cause theLEDto fail to light up or exhibit abnormal brightness; - The keys are configured with pull-up input (
Pin.PULL_UP), and the pin level goes low when a key is pressed. If the key does not respond, check whether the pin is connected reversely or verify the interrupt trigger mode (which is set toPin.IRQ_FALLINGin the code).
- Common cathode
- Software Version Related:
- It is required to use
MicroPython v1.23.0or a newer version; lower versions may not supportdeque(filter buffer), soft timer scheduling, or some methods of themachinemodule. scheduler.pyrelies on a software timer (Timer (-1)). If the development board does not support software timers, you need to modify it to a hardware timer (e. g.,Timer (0)) and ensure that the timer number is not occupied;- Debug logging (
ENABLE_DEBUG= True) consumes a certain amount of memory and serial port bandwidth. It is recommended to disable it (ENABLE_DEBUG= False) in formal use to improve system operating efficiency.
- It is required to use
- Function Usage Notes:
- Task cycle (
sensor_task'sinterval= 200ms) is not recommended to be modified to ≤100ms, otherwise it may lead to incomplete sensor reading or frequent hardware control, increasing theCPUload; - Automatic
GCthreshold (GC_THRESHOLD_BYTES) is recommended to be set to 100000-200000 bytes. An excessively low threshold will causeGCto be triggered frequently (affecting real-time performance), while an excessively high threshold will lead to out-of-memory crashes; - If the development board has no onboard
SDcard, you need to setHAS_SD= Falsein theDEFAULTSsection ofboard.pyto avoid errors duringSDcard initialization (theget_sd_spi_configfunction in the code will not affect core functions, but will print a warning).
- Task cycle (
11. Version Record
- v1.0.0 (2025-09-11): Li Qingshui completed the initial version, implemented basic functions and wrote the documentation, however
toolsthe functions in the folder that automatically analyzes project dependencies and utilizesmpy-crossandmpremotetools to compile and batch upload mpy files have not been implemented:- Supports
RCWL9623real-time ranging and three-point mean filtering; - Implement
LEDluminance non-linear mapping and buzzer frequency linkage; - Supports task start/stop switching via key interrupt, automatic
GC, exception capture and error reporting; - Adapted to GraftPort-RP2040 development board, complete drivers and task code are provided.
- Supports
12. Contact the Developer
If you have any questions or need assistance, please contact the developer via the following channels :
📧 Email: 10696531183@qq.com
💻 GitHub: https://github.com/FreakStudioCN
13. Licensing Agreement
In this project, except for machine and other MicroPython official modules (under the MIT license), all driver and extension codes written by the author are released under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) Licensing Agreement.
You are free to:
- Share — to copy, distribute the work in any medium or in any form
- Derivative Works — modify, transform, or create based on this Work
Only the following conditions shall be complied with:
- Attribution — You must give appropriate credit, provide a link to the Licensing Agreement, and indicate if changes were made. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
- Non-commercial Use — You may not use this work for commercial purposes.
- Proper Citation Method — You may clearly indicate the source in code comments, documentation, demo videos, or project descriptions.
Copyright belongs to FreakStudio.
Appendix I: Project Source Code Download
https://github.com/FreakStudioCN/GraftPort_MicroPython_Labs/tree/main/proximity_music_light
proximity_music_light.rar 22.4 MB
Appendix II: Hardware Module Reference Materials
GraftSense - Piranha LED Module;
GraftSense - Passive Buzzer Module
GraftSense-SY7656 Lithium Battery Charge-Discharge Module
GraftPort - Raspberry Pi Pico Expansion Board (Internal Edition Template Files)
Version Record
Document Version | Date of Modification | Modifier | Modified Content |
V1.0.0 | 2025-09-11 | Li Zisheng | Draft the initial version of the document. |
V1.1.0 | 2026-01-04 | Li Zisheng | Final version. |