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. Precautions
- 11. Version Record
- 12. Contact the Developer
- 13. Licensing Agreement
- Appendix 1: Project Source Code Download
- Appendix II: Hardware Module Reference Materials
- Version Record


Project Description
1. Introduction
1.1 Project Background
Traditional light detection devices usually have a single function and lack intuitive visual display of light intensity. This project is based on the GraftPort-RP2040 development board, and combines the light intensity sensor module based on the BH1750 chip and the 8-segment light bar digital tube module based on the PCF8574 chip to realize an integrated system of "light intensity detection and visual display", which intuitively presents the current light intensity through an LED bar graph. Meanwhile, it integrates 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 based on MicroPython development, the core function is through the light intensity sensor module based on the BH1750 chip real-time detection of ambient light intensity (unit: lux ), based on the PCF8574 chip eight-segment light bar digital tube module in the form of a bar graph visual display of light intensity level; support onboard key interrupt switching task start and stop, built-in automatic garbage collection ( GC ) to avoid memory leaks, abnormal capture and speed limit printing for problem location.
1.3 Applicable Scenarios or Application Area
- Intelligent Lighting Control: Automatically adjusts the display based on ambient light intensity
LED, for smart home lighting systems; - Environmental Monitoring: As a portable light intensity monitoring device, it is applied for agricultural greenhouses and indoor light adjustment;
- Teaching Demonstration: Applied to
MicroPythontask scheduling,I2Ccommunication, sensor Data Acquisition and other knowledge points for practical teaching; - Art Installation: Integrated into interactive art installations to generate visual feedback in response to changes in ambient light.
2. Main Functions
- Real-time light intensity detection: via the light intensity sensor module based on the BH1750 chip to collect the ambient light intensity in real time, with a measurement range
of 0-65535 lux; - LED Bar Graph Display: An 8-segment bar LED module based on the PCF8574 chip that dynamically displays the corresponding level according to the light intensity;
- Self-Adaptation Range: Light intensity is automatically mapped to
0-8 LEDlevels (0-2000 lux range), and automatic amplitude limiting will be triggered when out of range; - 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 usage is below the threshold, to preventMicroPythonfrom 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 avoid excessive log spamming;
- Flexible board-level adaptation: Based on
board.pyto realize pin mapping decoupling, and supports 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 - Light Intensity Sensor Module Based on BH1750 Chip (
I2CCommunication, Default Address0x23); - GraftSense - An 8-segment bar digital tube module based on the PCF8574 chip (which controls an 8-segment
PCF8574module to drive anLEDbar display, with a default address of0x20); - 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 Connections
Light intensity sensor module based on BH1750 chip: connected via PH2.0 connecting cable to I2C0 interface;
8-segment bar LED digital tube 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 casing (M3 screw holes are pre-reserved on both the main control board and the casing):


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 shall be turned on:

The lithium battery charge-discharge module supports power level display and can be charged via the Type-C port below:

BH1750defaultI2Caddress is0x23, which will be automatically scanned and identified upon system startup;PCF8574defaultsits I2Caddress to0x20, supports the address range of0x20-0x27, which will be automatically detected by the system.
4. Software Environment
- Core Firmware:
MicroPython v1.23.0(requires adaptation forGraftPort-RP2040, with support formachine.Pin/I2C/Timermodules); - Development IDE:
PyCharm(for code writing, uploading and debugging, supportingMicroPython REPLinteraction); - Auxiliary 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);
- Dependencies: No additional third-party libraries are required; all drivers are custom-implemented and provided along with the project files.
5. File Structure
light_intensity_display
├─ .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
│ └─ drivers
│ ├─ __init__.py
│ ├─ pcf8574_led_driver
│ └─ BH1750_driver
└─ examples
└─ README.md
6. Description of Key Documents
main.py: Project entry point, with core logic including:- Power on and delay for 3 seconds (wait for hardware to stabilize), initialize the onboard
LED,I2Cbus, and buttons (including interrupt registration); - Hardware initialization: scan
I2Cbus to identifyBH1750andPCF8574device addresses; - Create
BH1750sensor andPCF8574 LEDdriver instances; - Create
sensor_taskinstance (pass in hardware driver and configuration parameters), and encapsulate it as a scheduler task with a period of 10ms; - Initialize
Scheduler(software timer with a scheduling period of 5ms), 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 hardware to stabilize), initialize the onboard
tasks/sensor_task.py: Core business task. Key logic of thesensorTaskclass:__init__: Initializethe BH1750sensor andLEDBarinstance, and configure the sensor measurement mode (single measurement, high resolution);tick: Executed once every 10ms, the process is "read the light intensity → calculate theLEDdisplay level → update theLEDbar graph display";- Illuminance intensity mapping:
0-2000 luxis linearly mapped to the range of0-8LEDlevels, and automatic clipping will be applied for values beyond the range.
tasks/maintenance.py: System maintenance module, key functions:task_idle_callback: Triggered when the scheduler is idle; if the detected memory is belowGC_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 log flooding;- Supports reading configurations from
conf.py, and uses default values when no configuration is available to ensure compatibility.
drivers/xxx_driver: hardware driver modules, all adopting the "instantiation + method call" pattern:BH1750_driver:The BH1750class communicates viaI2Cto provide ambient light intensity measurement, supporting both single and continuous measurement modes;pcf8574_led_driver:The PCF8574class implementsI2C-controlledIOexpansion, and theLEDBarclass provides 8-segmentLEDbar graph display control.
board.py: Board-level pin mapping module, which defines theBOARDSdictionary (including the fixed pins ofGraftPort-RP2040and theI2Cinterface mapping), provides interfaces such asget_fixed_pin and get_i2c_pins, and realizes the decoupling of board-level configuration and business logic.conf.py: A user configuration file. The parameters that require manual definition by the user include:ENABLE_DEBUG(debug print switch),AUTO_START(whether the task starts automatically). If not defined, the system will use the default value.
7. Core Idea of Software Design

- Hierarchical System Design Concept: Adopts a "four-tier architecture" to achieve decoupling and reusability
- Hardware Driver Layer (
drivers/): only responsible for the low-level control of hardware; for example, theBH1750driver only focuses on "how to obtain ambient light data", and thePCF8574driver only focuses on "how to controlLEDs"; - Task Logic Layer (
tasks/): Implements business logic based on the driver layer interfaces. For example,sensorTaskcallsBH1750to acquire light intensity data and callsLEDBarto control display, without concerning itself with specific hardware details; - Scheduling Control Layer (
libs/scheduler.py): Provides general task management capabilities, supports task addition/pause/resume, and uniformly manages task execution timing through a soft timer; - Entry Layer (
main.py): responsible for hardware initialization, task creation and scheduling startup, serving as the "glue code" of the system.
- Hardware Driver Layer (
- Principles for Module Division: High cohesion, low coupling, to facilitate maintenance and expansion
- High Cohesion: each module has a single responsibility;
maintenance.pyonly handles system maintenance,sensor_task.pyonly handles the light Data Acquisition and display logic; - Low coupling: Modules interact through interfaces, for example,
sensorTaskobtains data viaBH1750.measurementand controls the display viaLEDBar.display_level (); - Scalability: When adding a new sensor, you only need to add the corresponding driver under
drivers/and create a new task undertasks/, without modifying existing code.
- High Cohesion: each module has a single responsibility;
- Core Mechanism: Ensuring System Stability and User Experience
- Task scheduling mechanism: Implemented based on a soft timer, with a scheduling cycle of 5ms and a core task cycle of 10ms; the task execution time is determined via "counter accumulation";
- Dynamic Display Mechanism: The light intensity is mapped to the
LEDbar graph in real time, providing intuitive visual feedback of the light intensity; - Interactive Feedback Mechanism: Instant response to key interrupts, supporting pause/resume of Data Acquisition and display update at any time;
- Fault-tolerant mechanism: Key operations are wrapped with
try-except, with automatic scanning and address identification forI2Cdevices, so hardware faults will not affect the basic operation of the system.
- Task Execution Process:

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 Run Device (Target Device) as RP2040, and enable the Auto-detect device path (Auto-detect device path) option.

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, 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
- Light intensity detection: block the sensor with your hand or shine a light source onto it
BH1750sensor, and observe the changes on theLEDbar graph display;
- Key Control: Press the onboard key to pause the task (stop Data Acquisition and display update); press it again to resume;
- Intensity Mapping: Observe the correspondence between the number of illuminated LEDs under different light intensities (
0-250 luxilluminates 1LED, and1750-2000 luxilluminates 8LEDs).
8.5 Debugging and Troubleshooting
- If
the I2Cdevice does not respond, check the hardware connections, power supply, andI2Caddress configuration; - If the
PCF8574LEDdoes not light up, check whether theI2Caddress is correct (0x20~0x27), and use anI2Cscanner to confirm the device address; If BH1750, checkthe I2Caddress to confirm it is correct (0x23), and useI2Cscan to verify the device address;
9. Sample Program
There are no other reference sample codes for this project, and you can directly make modifications in the project folder.
10. Precautions
- Sensor-related:
- The light intensity sensor module based on
the BH1750chip requires an appropriate measurement duration, and the single measurement mode needs to wait until the measurement is completed; - The sensor shall be protected from direct strong light to avoid damage or inaccurate measurement.
- The light intensity sensor module based on
- Hardware Connection:
The I2Cdevice address may vary depending on the module version, and the system will automatically scan and identify it;The PCF8574module has limited output current and is not suitable for directly driving high-powerLEDs.
- Software Version Related:
- Must use
MicroPython v1.23.0and above; - Debug printing consumes a certain amount of memory, so it is recommended to disable it in official use.
- Must use
- Function Usage Related:
- The task cycle (10ms) can be adjusted according to actual needs; an excessively small cycle may increase the system load.
LEDdisplay level mapping range (0-2000 lux) can be adjusted according to the application scenario.
11. Version Record
- v1.0.0 (2025-09-09): Initial version completed by Li Qingshui:
- Supports
BH1750real-time ambient light intensity detection; - Implement
PCF8574-controlled 8-segmentLEDbar graph display; - Supports key interrupt to switch task start and stop;
- Adaptation is based on the GraftPort-RP2040 development board.
- 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 — to modify, transform, or build upon the Material
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 © FreakStudio. All rights reserved.
Appendix 1: Project Source Code Download
https://github.com/FreakStudioCN/GraftPort_MicroPython_Labs/tree/main/light_intensity_display
Appendix II: Hardware Module Reference Materials
GraftSense - A Light Intensity Sensor Module Based on the BH1750 Chip
GraftSense - An 8-segment bar digital tube module based on the PCF8574 chip
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 | Modify Content |
V1.0.0 | 2025-11-03 | Junhan Hou | Draft the document. |
V1.1.0 | 2026-01-04 | Li Zisheng | Final version. |