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

Project Description
1. Introduction
1.1 Project Background
Traditional signal generator devices are usually bulky, complicated to operate and expensive.This project is based on the GraftPort-RP2040 development board, and integrates a clock signal generation module based on the SI5351 chip, a 5-way button module based on the PCF8574 and a 0.96-inch SSD1306-OLED module to realize an integrated programmable signal generator system featuring "frequency setting - channel selection - signal output", which addresses the issues of complex operation and poor portability of professional signal source equipment; meanwhile, it incorporates MicroPython lightweight task scheduling and menu interaction mechanisms to deliver a user-friendly operating experience.
1.2 Overview of the Main Functions of the Project
This project is developed based on MicroPython. Its core function is to generate programmable frequency signals via the SI5351 chip, and provide an interactive menu interface through the OLED display. Users can set the output frequency, select the output channel, and control the start/stop of signal output via a 5-way button; it also supports on-board button interrupt to switch task start/stop, has built-in automatic garbage collection to avoid memory leaks, and is equipped with exception capture and rate-limited printing for easier problem locating.
1.3 Applicable Scenarios or Application Area
- Electronic Experiment: Provides a signal source with adjustable frequency for circuit testing;
- Teaching Demonstration: Applied for teaching demonstrations of digital circuits and frequency synthesis principles;
- RF Development: Serves as a low-cost RF signal source for prototype development;
- Instrument Calibration: Provides reference signal sources for other testing equipment.
2. Main Functions
- Programmable signal output: via the clock signal generation module based on the SI5351 chip, it supports programmable signal output in the frequency range of 0-20MHz, and is equipped with three independent output channels;
- OLED Menu Interaction: A four-level menu system (frequency setting, output channel, output enable, output stop) is provided via the 0.96-inch SSD1306-OLED module;
- 5-way key control: implemented via the 5-way key module based on PCF8574 to realize menu navigation and parameter adjustment;
- Multi-channel Output Management: Supports individual control of three independent output channels, with configurable frequency and start/stop status for each channel separately;
- Key press interrupt interaction: The onboard key triggers a falling-edge interrupt, which can toggle the core task between "running/paused";
- Automatic memory management: detects memory usage when idle, and automatically triggers
GCif the memory is below the threshold, preventingMicroPythonfrom crashing due to memory leaks; - Exception Fault Tolerance Mechanism: When an exception is thrown during task execution, the stack trace will be fully printed with rate limiting enabled to prevent log spamming;
- Flexible board-level adaptation: based on
board.pyto realize pin mapping decoupling, supporting subsequent expansion to otherRP2040development boards.
3. Hardware Requirements
3.1 Hardware Required
The project is based on the GraftPort-RP2040 development board as the main controller:

The other required modules include:

- GraftSense-SI5351 Programmable Clock Generator Module:(
I2CCommunication, Address0x60or0x61); - GraftSense-PCF8574 5-way key module:(
I2Ccommunication, address range0x20–0x27); - GraftSense 0.96-inch SSD1306 OLED module:(
I2Ccommunication, address0x3Cor0x3D); - GraftSense 6-Channel 12C Direct Connection Expansion Module:
I2Cbus interface expansion; - GraftSense-SY7656 Lithium Battery Charge-Discharge Module:(compatible with polymer lithium batteries, outputs 5V voltage, equipped with a
Type-Ccharging port); - Onboard buttons: By default, the fixed pins of the development board (Pin 18, pull-up input) are used, and no additional wiring is required;
- Onboard LED: By default, it uses the fixed pin (Pin 25) of the development board, and no additional wiring is required.
3.2 Hardware Connection
PCF8574 5-way key module: connect it via PH2.0 connecting cable to the I2C expansion module;
0.96-inch SSD1306-OLED module: connected to the PH2.0 connecting cable I2C expansion module;
6-channel 12C Direct Connection Expansion Module: Connect to the PH2.0 connection cable I2C0 interface

GtaftSense-SI5351 Programmable Clock Generator Module: connected via PH2.0 connecting cable to I2C1 interface;

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



3.3 Structural Assembly
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 periphery of the housing with M3 plastic pillars, then screw in M3 screws at 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 Type-C interface below:

4. Software Environment
- Core Firmware:
MicroPython v1.23.0(adaptation required forGraftPort-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 to. 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
square_wave_generator
├─ .flake8
├─ LICENSE
├─ README.md
├─ tools
│ ├─ dependency_analyzer.py
│ ├─ mpy_compiler.py
│ ├─ mpy_uploader.py
│ └─ README.md
├─ firmware
│ ├─ board.py
│ ├─ boot.py
│ ├─ conf.py
│ ├─ main.py
│ ├─ tasks
│ │ ├─ maintenance.py
│ │ ├─ sensor_task.py
│ │ └─ __init__.py
│ ├─ libs
│ │ ├─ __init__.py
│ │ ├─ scheduler
│ │ └─ oledmenu
│ └─ drivers
│ ├─ __init__.py
│ ├─ ssd1306_driver
│ ├─ si5351_driver
│ └─ pcf8574keys_driver
└─ examples
└─ README.md
6. Description of Key Documents
main.py: the project entry point, whose core logic includes:- Power on and delay for 3 seconds (wait for hardware to stabilize), initialize the onboard
LED,OLED,SI5351,PCF8574key module and keys (including interrupt registration); - Hardware initialization:
I2Cbus scan to automatically identify device addresses,OLEDmenu system initialization; - Create
sensor_taskinstance (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 fatal error handling).
- Power on and delay for 3 seconds (wait for hardware to stabilize), initialize the onboard
tasks/sensor_task.py: core business task,key logic of the sensorTask class:__init__: Initialize the hardware instance, create a four-level menu system, and configurethe SI5351 PLLand output channels;tickExecuted every 200 ms, the process is "read key status → menu navigation → parameter setting → signal output control";- Menu callback functions:
show_freq(set frequency),sw_output(select output channel),show_output(enable output),show_stop(stop output).
tasks/maintenance.py: System maintenance module, key functions:task_idle_callbackTriggered when the scheduler is idle; if the detected 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, it prints the full traceback (preferentially viasys.print_exception), then delays forERROR_REPEAT_DELAY_S(1 second by default) to prevent screen flooding;- Supports reading configuration from
conf.py, uses default values when no configuration is available to ensure compatibility.
drivers/xxx_driver: hardware driver modules, all adopting the "instantiation + method call" pattern:si5351_driver:The SI5351_I2Cclass controls the clock generator viaI2Cand provides methods includingsetup_pll,init_clock,set_freq_fixedpll,enable_outputand others;pcf8574keys_driver:PCF8574Keysclass reads the status of the 5-way keys viaI2C, and theread_allmethod returns a dictionary containing the status of all keys;ssd1306_driver:The SSD1306_I2Cclass controlsI2C-basedOLEDdisplays and provides methods includingfill,text,show, etc.oledmenu:The SimpleOLEDMenuclass implements anOLEDmenu system that supports menu addition, navigation, display, and callback execution.
board.py: A board-level pin mapping module that defines theBOARDSdictionary (including the fixed pins ofGraftPort-RP2040and theI2Cinterface mapping), and provides interfaces such asget_fixed_pinandget_i2c_pinsto achieve "decoupling of board-level configuration and business logic".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 Ideas of Software Design

- System Hierarchy Concept: Adopt a "four-tier architecture" to achieve decoupling and reuse
- Hardware Driver Layer (
drivers/): It is only responsible for the low-level control of hardware. For example, theSI5351driver only focuses on "how to set the frequency" and does not care about "how users operate". - Task Logic Layer (
tasks/): Implements business logic based on the driver layer and menu system. For example,sensorTaskresponds to user operations via menu callbacks and invokes theSI5351driver to configure parameters. - Scheduling Control Layer (
libs/scheduler.py): Provides universal task management capabilities, supporting task addition/pause/resume, as well as idle and exception callbacks. - Entry Layer (
main.py): responsible for "assembling" all layers, following the process of initializing hardware → creating tasks → starting scheduling; it acts as the "glue" of the system.
- Hardware Driver Layer (
- Principles for Module Division: High cohesion, low coupling, facilitating easy maintenance and expansion
- High Cohesion: each module is only responsible for the Single Responsibility Principle, for example,
maintenance.pyonly handles system maintenance,sensor_task.pyonly handles user interaction and signal control. - Low coupling: Modules interact through "interfaces", for example,
sensorTaskobtains the key status viaPCF8574Keys.read_all(), without directly operating theI2Chardware. - Scalability: To add a new feature, you only need to add a new item and the corresponding callback to the menu system, without modifying the existing architecture.
- 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, with a scheduling cycle of 50ms and a core task cycle of 200ms; the timing for task execution is determined via "counter accumulation".
- Menu interaction mechanism: The four-level menu features a clear structure, intuitive five-way button operation, and real-time display of current status and parameters.
- Frequency control mechanism: supports precise adjustment in the range of 0-20MHz, with three output channels controlled independently,
PLLconfiguration ensures frequency stability. - Fault-tolerant mechanism:
I2C device automatic address identification, LED flashing prompt for abnormal conditions, and key operation exception capture to prevent system crashes.
- Task execution process: The task execution process is shown below:

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:
- Menu Navigation: Use the 5-way button to select menu items up and down, adjust parameters left and right,
SW1to confirm,SW2to return; - Frequency Setting: Set the output frequency (in the range of 0-20MHz) in the
freqmenu; - Channel Selection: Select the output channel (0-2) from the
Outputmenu; - Signal Output: Enable the signal output of the selected channel via the
Openmenu, and stop the output via theStopmenu;
- The oscilloscope outputs and correctly displays a waveform with a frequency of 12Mhz according to the settings:

- Mission Control: Press the onboard button to pause the mission (stop menu response), and press it again to resume.
When conf.py is configured unchanged and the hardware connection is normal, the program can run properly.
The terminal output is as follows:

8.5 Debugging and Troubleshooting
- If the function malfunctions, ensure that
ENABLE_DEBUG = True, and then check the debug information in the terminal; - If
I2Cdevice does not respond, check the hardware connection, power supply, andI2Caddress configuration; - If
OLEDdoes not display, check whether theI2Caddress is correct (0x3cor0x3d) and whether theI2Cbus is normal; - If
SI5351has no output, check thePLLconfiguration, frequency settings and output enable status.
9. Sample Program
There are no other reference sample codes for this project, you can directly make modifications in the firmware folder.
10. Notes
- Sensor-related:
- The output frequency range is limited by the
SI5351chip, with a maximum of approximately 200MHz, and this project limits it to 0-20MHz; - Reconfiguration is required during frequency switching
PLL, which will result in a short period of frequency instability.
- The output frequency range is limited by the
- Hardware Connection Related:
I2Cdevice addresses may vary by manufacturer, and the system will automatically scan and identify them;The SI5351module requires a stable power supply to avoid frequency jitter.
- Software Version Related:
MicroPython v1.23.0 or later version must be used;- Debug printing consumes a certain amount of memory, so it is recommended to disable it in formal use scenarios.
- Function Usage Related:
- Task period (200ms) is not recommended to be set too small, otherwise it may affect the key response;
- The frequency setting step is 1 MHz, and the adjustment step in the code can be modified as required.
11. Version Record
- v1.0.0 (2025-10-10): Initial version completed by Hou Junhan, with basic functions implemented and documentation prepared:
- Supports
SI5351programmable signal output - Implement
OLEDfour-level menu interaction system - Supports 5-way button navigation and parameter adjustment
- Realize three-channel independent output control
- 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 (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 — copy, distribute the work in any medium or in any form
- Derivative Works — to modify, transform, or create based on the 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 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.
- 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 © FreakStudio. All rights reserved.
Appendix 1: Project Source Code Download
https://github.com/FreakStudioCN/GraftPort_MicroPython_Labs/tree/main/square_wave_generator
Appendix II: Reference Materials for hardware Modules
GraftSense-SI5351 Programmable Clock Generator Module
GraftSense-PCF8574 5-direction Button Module
GraftSense 0.96-inch SSD1306 OLED Module
GraftSense 6-Channel 12C Direct Connect Expansion Module
GraftSense-SY7656 Lithium Battery Charge-Discharge Module
GraftPort - Raspberry Pi Pico Expansion Board (Open Edition Template Files)
Version Record
Document Version | Date of Revision | Modifier | Revised Content |
V1.0.0 | 2025-11-03 | Hou Junhan | Draft the initial version of the document. |
V1.1.0 | 2026-01-04 | Li Zisheng | Final version. |