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 environmental monitoring devices mostly feature fixed displays or single functions, and lack the capabilities of real-time data display and wireless transmission.This project is based on the GraftPort-RP2040 development board, and integrates the UV ultraviolet sensor module based on GUVA-S12SD, the master-slave integrated BLE Bluetooth module based on HC-08 and the 0.96-inch SSD1306-OLED module to realize an integrated system of "ultraviolet index detection - display - wireless transmission", which solves the problem of single function of traditional environmental monitoring equipment. Meanwhile, it incorporates MicroPython 's lightweight task scheduling and exception handling mechanism to ensure the stable operation of the system.
1.2 Overview of the Main Functions of the Project
This project is developed based on MicroPython, whose core function is to use the UV ultraviolet sensor module based on GUVA-S12SD to detect ultraviolet intensity in real time and convert it into the ultraviolet index (UVI), display it in real time on the OLED display screen, and transmit data wirelessly via the master-slave integrated BLE Bluetooth module based on HC-08; it supports on-board key interrupt to switch task start and stop, has built-in automatic garbage collection (GC) to avoid memory leaks, and is equipped with exception capture and rate-limited printing to facilitate problem locating.
1.3 Applicable Scenarios or Application Area
- Outdoor Activities: Monitor UV intensity in real time and remind users to take proper sun protection measures;
- Environmental Monitoring: As a portable ultraviolet monitoring device, it is applied in meteorological observation and environmental research.
- Teaching Demo: for
MicroPythontask scheduling,ADCData Acquisition,UARTcommunication,I2Cdisplay and other knowledge points in practical teaching; - Smart Wearables: Integrated into wearable devices to provide UV protection reminder functions.
2. Main Functions
- Real-time UV index detection: The system uses the GUVA-S12SD sensor to collect UV intensity every 200ms and convert it into the standard ultraviolet index (
UVI); - OLED real-time display: via the 0.96-inch SSD1306-OLED module to display the current ultraviolet index in real time, and the display will be updated immediately when the data changes;
- Bluetooth wireless transmission: via the master-slave integrated BLE Bluetooth module based on HC-08 to transmit the ultraviolet index data wirelessly to other devices;
- Key Interrupt Interaction: The onboard key triggers a falling-edge interrupt, which can switch the core task between "run/pause"; when paused, Data Acquisition and display update will be stopped.
- 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 - UV ultraviolet sensor module based on GUVA-S12SD:(analog output, connected to
ADCpin); - GraftSense - HC-08 based master-slave integrated BLE Bluetooth module:(
UARTcommunication, defaultbaud rate 9600); - GraftSense 0.96-inch SSD1306 OLED module:(
I2Ccommunication, address0x3Cor0x3D); - 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
UV ultraviolet sensor module based on GUVA-S12SD: connected via PH2.0 connecting cable to ADC0 interface;
HC-08-based master-slave integrated BLE Bluetooth module: connected via PH2.0 connecting cable to UART0 interface;
0.96-inch SSD1306-OLED module: connected via PH2.0 connecting cable to the I2C0 interface
Lithium battery charge-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 can be charged via the Type-C interface below:

4. Software Environment
- Core Firmware:
MicroPython v1.23.0(adaptation forGraftPort-RP2040is required, with support formachine.Pin/I2C/UART/ADC/Timermodules); - Development IDE:
PyCharm(used for code writing, uploading and debugging, and supportsMicroPython REPLinteraction); - Accessory Tools:
Python 3.12+(optional, for running local helper 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 are custom-implemented and provided along with the project files.
5. File Structure
uv_Intensity_bluetooth
├── .flake8 # Python code style check configuration file (PEP8 standard)
├── LICENSE # License file (CC BY-NC 4.0)
├── README.md # Project documentation (this document)
├── tools/ # Development helper tool scripts
│ ├── dependency_analyzer.py # Project dependency analysis tool (checks reference relationships between modules)
│ ├── mpy_compiler.py # Tool for batch compiling .py files to .mpy (reduces memory usage)
│ ├── mpy_uploader.py # Script that uploads .mpy files to the development board via mpremote
│ └── README.md # Tool usage documentation
├── firmware/ # Firmware code directory (files to be uploaded to the development board)
│ ├── board.py # Board-level pin mapping file (defines the hardware interfaces of the GraftPort-RP2040)
│ ├── boot.py # MicroPython boot script (empty by default, initialization logic can be customized)
│ ├── conf.py # System configuration file (debug switch, GC threshold, and other parameters)
│ ├── main.py # Project entry file (hardware initialization, task creation, scheduler startup)
│ ├── tasks/ # Task logic module
│ │ ├── maintenance.py # System maintenance tasks (automatic GC, exception handling callbacks)
│ │ ├── sensor_task.py # Core tasks (UV acquisition, OLED display, Bluetooth transmission)
│ │ └── __init__.py # Package initialization file
│ ├── libs/ # Common utility library
│ │ ├── __init__.py # Package initialization file
│ │ └── scheduler/ # Task scheduler
│ │ ├── scheduler.py # Scheduler core implementation (adding/pausing/resuming tasks, periodic scheduling)
│ │ └── __init__.py # Package initialization file
│ └── drivers/ # Hardware driver modules (classified by device)
│ ├── __init__.py # Package initialization file
│ ├── ssd1306_driver/ # SSD1306 OLED driver
│ ├── hc08_driver/ # Master-slave integrated BLE Bluetooth module driver based on HC-08
│ └── gUVa_s12sd_driver/ # GUVA-S12SD UV sensor driver
├── examples/ # Example code directory (reserved for extension)
│ └── README.md # Example documentation
└── docs/ # Project documentation directory
# Holds documents such as hardware wiring diagrams, design notes, module datasheets, and development board pin tablesIf you want to add other sensor modules to the main control board, it is recommended that you check docs the file under the folder graftport_pinout_table.md to view the pin mapping.
6. Description of Key Documents
main.py: Project entry point, with core logic including:- Power-on delay for 3 seconds (wait for hardware to stabilize), initialize the onboard
LED,OLED,UVintensity sensor,HC-08Bluetooth module, and buttons (including interrupt registration); - Hardware initialization:
OLED,UVlight intensity sensor,HC-08Bluetooth module - 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 delay for 3 seconds (wait for hardware to stabilize), initialize the onboard
tasks/sensor_task.py: Core business task. Key logic of theuvOledTaskclass:__init__: Initialize the hardware instance;tick: executed once every 200ms, with the process being "readUVlight intensity → send data packet →OLEDupdate display";
tasks/maintenance.py: System maintenance module, key function: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: a hardware driver module, which all adopts the "instantiation + method call" mode, only exposes hardware-related control interfaces and shields underlying details:hc08_driver:The HC08class communicates via UART serial port, and thesend_datamethod is used to send binary data.ssd1306_driver:The SSD1306_I2Cclass controls OLED display via I2C and provides methods includingfill,text,show, etc.guva_s12sd_driver:The GUVA_S12SDclass reads analog voltage values via ADC, and theuviattribute returns the calculated ultraviolet index.board.py- Board-Level Pin Mapping Module
board.py: a board-level pin mapping module that defines theBOARDSdictionary (including the fixed pins ofGraftPort-RP2040and 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 support for other development boards later, you only need to add sub-items toBOARDS.conf.py: A user configuration file. The parameters that require manual definition by the user include:I2C_INIT_MAX_ATTEMPTS(number of retries for sensor initialization),I2C_INIT_RETRY_DELAY_S(interval between retries in seconds),ENABLE_DEBUG(debug print switch),AUTO_START(whether the task starts automatically). If left undefined, the system will use the default values.
7. Core Ideas of Software Design

- System layering concept: Adopt a "four-tier architecture" to achieve decoupling and reuse
- Hardware Driver Layer (
drivers/): only responsible for the low-level control of hardware, and contains no business logic. For example, the UV sensor driver only cares about "how to obtainUVlight intensity", and does not care about "when to display it". - Task Logic Layer (
tasks/): Implements business logic based on the interfaces provided by the driver layer. For example,uvOledTaskonly calls theuviattribute to obtain data, without concerning itself with the sensor'sADCpin; it only callssend_datato transmit data, without concerning itself with the BluetoothUARTconfiguration; it only callstextandshowto display content, without concerning itself with theOLED'sI2Caddress. - Scheduling Control Layer (
libs/scheduler.py): It provides general task management capabilities, supports task addition/pause/resume, idle/exception callbacks, and is independent of specific services; it uniformly manages the execution timing of all tasks through a soft timer to ensure rational allocation of system resources. - Entry layer (
main.py): responsible for "assembling" all layers, initializing hardware → creating tasks → starting scheduling; it acts as the "glue" of the system and contains no core business logic; it handles hardware exceptions and user interactions to ensure the stable startup and operation of the system.
- Hardware Driver Layer (
- Principles for Module Division: High cohesion, low coupling, to facilitate maintenance and expansion
- High Cohesion: Each module is only responsible for the Single Responsibility Principle, e. g.,
maintenance.pyonly handles system maintenance (GC, exceptions) and does not involve data display;sensor_task.pyonly handles the logic of UV Data Acquisition and display, and does not care about hardware initialization; each driver module only encapsulates the control methods for the corresponding hardware. - Low coupling: Modules interact through "interfaces" instead of directly manipulating internal variables, for example,
uvOledTaskacquires data viaGUVA_S12SD.uviwithout directly accessingADCregisters; sends data viaHC08.send_data ()without directly operating theUARThardware; displays content viaSSD1306_I2C.text ()without directly controllingI2Ccommunication. - Scalability: When adding new hardware (such as temperature and humidity 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 pin mappings inboard.pywithout affecting the business logic; when adding new display content, only modify the display logic ofuvOledTaskwithout involving changes at the hardware layer.
- High Cohesion: Each module is only responsible for the Single Responsibility Principle, e. g.,
- 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 through "counter accumulation" to avoid timer nesting conflicts; it supports dynamic task pause and resume to respond to user operations. - Data update mechanism: Adopts a "change detection" strategy, updating only when the UV index actually changes
OLEDdisplay, which not only reduces unnecessary screen refreshes (extendingOLEDlifespan) but also ensures real-time data display; it avoids system load and visual flicker caused by frequent refreshes. - Interactive feedback mechanism: Key interrupt callbacks take "immediate effect": when paused, Data Acquisition and display update stop immediately to avoid unresponsive user operations; when sensor initialization fails, "explicit error reporting"(
LEDflashing + terminal messages) is provided to facilitate troubleshooting of hardware connection issues; Bluetooth data transmission adopts a fixed format to ensure consistency of parsing at the receiving end. - Fault-tolerant mechanism: All key operations (such as hardware control, data reading) are wrapped with
try-exceptto prevent the failure of a single module from causing the entire system to crash. For example,OLEDdisplay failure will not affect Bluetooth data transmission;ADCreading exception will not affect the operation of task scheduling; the automatic memory recovery mechanism prevents memory leakage during long-time operation.
- 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 as RP2040, and enable Auto-detect device path.

Set Project/firmware as the project root directory.

Modify runtime configuration:

- Check
Allow multiple instances - Select
Store as project file - Click
OKto 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 and 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
- Ultraviolet detection: Expose the ultraviolet sensor to ultraviolet rays of different intensities and observe
OLEDwhether the display changes accordingly; - Bluetooth transmission: Use a Bluetooth receiving device to verify whether data is transmitted correctly;
- Button Toggle: Press the onboard button to pause the task (stop Data Acquisition and display update), and press it again to resume.
Access the Bluetooth debugging information interface:

8.5 Debugging and Troubleshooting
- If the function malfunctions, ensure that
ENABLE_DEBUG = True, then check the debug information in the terminal (e. g., "UV Level: value") to determine whether the data is normal; - If the sensor fails to initialize, check the hardware connections, power supply and pin configuration;
- If
OLEDdoes not display, check whether theI2Caddress is correct (0x3cor0x3d) and whether the I2C bus is normal; - If Bluetooth data transmission fails, check the
UARTconnection, baud rate setting (9600) and whether the Bluetooth module is working properly;
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:
- UV ultraviolet sensor module based on GUVA-S12SD requires appropriate light conditions and shall not be used in a completely dark environment;
- The sensor should be prevented from being exposed to extremely strong ultraviolet rays for a long time to avoid damage.
- Hardware Connection Related:
- The master-slave integrated BLE Bluetooth module based on HC-08 has its
UARTcommunication baud rate must be set to9600; - The 0.96-inch SSD1306-OLED module has an
I2Caddress that may be0x3Cor0x3D, which will be automatically detected by the system.
- The master-slave integrated BLE Bluetooth module based on HC-08 has its
- 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:
- The task cycle (200ms) is not recommended to be set too small, otherwise it may increase the system load;
- Automatic
GCThe threshold is recommended to be adjusted according to the actual memory usage.
11. Version Record
- v1.0.0 (2025-11-03): Junhan Hou completed the initial version, implemented basic functions and wrote the documentation, but
the toolsfolder does not yet have the feature to automatically analyze project dependencies, utilize thempy-crossandmpremotetools to compile and batch uploadmpyfiles- Support Bluetooth data reception
- Support
UVlight intensity monitoring - Implement
OLEDdisplay screen light intensity control
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/uv_Intensity_bluetooth
Appendix II: Reference Materials for hardware Modules
GraftSense: An Open-Source UV Ultraviolet Sensor Module Based on GUVA-S12SD
GraftSense - HC-08 Based Master-Slave Integrated BLE Bluetooth Module (Open Version)
GraftSense 0.96-inch SSD1306 OLED Module (Open Version)
GraftPort - Raspberry Pi Pico Expansion Board (Internal Edition Template Files)
Version Record
Document Version | Date of Revision | Modifier | Revised Content |
V1.0.0 | 2025-11-03 | Hou Junhan | Draft the document. Upload the source code |
V1.0.1 | 2025-12-31 | Li Zisheng | Modify module document link |