MPR121 电容触摸键盘驱动 - MicroPython 版本
目录
简介
本驱动为 MPR121 电容触摸键盘芯片提供 MicroPython 接口。MPR121 是一款 12 通道电容触摸传感器控制器,支持通过 I2C 接口读取触摸状态、配置触摸阈值、获取滤波数据和基线数据。适用于电容触摸按键、滑条、触摸板等人机交互场景。
主要功能
- 支持 12 个独立电极通道的触摸检测
- 可配置每个电极的触摸和释放阈值(0-255)
- 提供滤波数据和基线数据读取接口
- 自动基线跟踪和噪声滤波
- 支持单个电极或全部电极的状态查询
- 完整的参数校验和异常处理
- 资源自动释放(deinit)
硬件要求
推荐测试硬件: - Raspberry Pi Pico / ESP32 / ESP8266 - MPR121 电容触摸传感器模块
引脚连接:
| MPR121 引脚 | 功能描述 | 开发板引脚(示例) |
|---|---|---|
| VCC | 电源正极(3.3V) | 3V3 |
| GND | 电源负极 | GND |
| SCL | I2C 时钟线 | GPIO 5 |
| SDA | I2C 数据线 | GPIO 4 |
| IRQ | 中断输出(可选) | - |
软件环境
- 固件版本:MicroPython v1.23.0 或更高版本
- 驱动版本:v1.0.0
- 依赖库:无(仅依赖 MicroPython 内置模块)
文件结构
mpr121_driver/
├── mpr121.py # MPR121 驱动核心文件
├── main.py # 测试示例程序
└── README.md # 本说明文档
文件说明
| 文件 | 说明 |
|---|---|
mpr121.py |
MPR121 驱动类,提供触摸检测、阈值配置、数据读取等接口 |
main.py |
完整测试程序,包含正常场景、边界场景、异常场景测试 |
README.md |
驱动使用说明文档 |
快速开始
1. 复制文件
将 mpr121.py 复制到开发板的根目录或 /lib 目录。
2. 硬件连接
按照上方引脚连接表连接 MPR121 模块与开发板。
3. 运行示例
将以下代码保存为 main.py 并运行:
# Python env : MicroPython v1.23.0
# -*- coding: utf-8 -*-
# @Time : 2026/04/26
# @Author : Mike Causer
# @File : main.py
# @Description : 测试 MPR121 电容触摸键盘驱动类的代码
# @License : MIT
# ======================================== 导入相关模块 =========================================
from machine import I2C, Pin
import time
from mpr121 import MPR121
# ======================================== 全局变量 ============================================
# I2C 设备地址
MPR121_I2C_ADDR = 0x5A
# 打印间隔控制
last_print_time = time.ticks_ms()
print_interval = 1000
# ======================================== 功能函数 ============================================
def print_all_filtered_data():
"""
打印所有电极的滤波数据(高频,默认注释调用,可 REPL 手动调用)
"""
print("Filtered data for all electrodes:")
for i in range(12):
data = mpr121.filtered_data(i)
print(" Electrode %d: %d" % (i, data))
def print_all_baseline_data():
"""
打印所有电极的基线数据(高频,默认注释调用,可 REPL 手动调用)
"""
print("Baseline data for all electrodes:")
for i in range(12):
data = mpr121.baseline_data(i)
print(" Electrode %d: %d" % (i, data))
def test_threshold_config():
"""
测试阈值配置(模式切换,默认注释调用,可 REPL 手动触发)
"""
# 测试设置所有电极阈值
print("Setting thresholds for all electrodes: touch=20, release=10")
mpr121.set_thresholds(20, 10)
# 测试设置单个电极阈值
print("Setting thresholds for electrode 0: touch=30, release=15")
mpr121.set_thresholds(30, 15, electrode=0)
# 恢复默认阈值
print("Restoring default thresholds: touch=15, release=7")
mpr121.set_thresholds(15, 7)
def test_boundary_parameters():
"""
测试边界参数(边界场景,默认注释调用,可 REPL 手动触发)
"""
print("Testing boundary parameters:")
# 测试电极边界值
print(" Reading electrode 0 (min)...")
data = mpr121.filtered_data(0)
print(" Filtered data: %d" % data)
print(" Reading electrode 11 (max)...")
data = mpr121.filtered_data(11)
print(" Filtered data: %d" % data)
# 测试阈值边界值
print(" Setting threshold to 0 (min)...")
mpr121.set_thresholds(0, 0, electrode=0)
print(" Setting threshold to 255 (max)...")
mpr121.set_thresholds(255, 255, electrode=0)
# 恢复默认阈值
mpr121.set_thresholds(15, 7)
print(" Boundary test completed")
def test_invalid_parameters():
"""
测试非法参数(异常场景,默认注释调用,可 REPL 手动触发)
"""
print("Testing invalid parameters:")
# 测试超出范围的电极编号
try:
mpr121.filtered_data(12)
print(" ERROR: Should raise ValueError for electrode 12")
except ValueError as e:
print(" OK: Caught ValueError for electrode 12: %s" % str(e))
# 测试超出范围的阈值
try:
mpr121.set_thresholds(256, 10)
print(" ERROR: Should raise ValueError for touch threshold 256")
except ValueError as e:
print(" OK: Caught ValueError for touch threshold 256: %s" % str(e))
# 测试错误类型的参数
try:
mpr121.is_touched("0")
print(" ERROR: Should raise ValueError for string electrode")
except ValueError as e:
print(" OK: Caught ValueError for string electrode: %s" % str(e))
print(" Invalid parameter test completed")
# ======================================== 自定义类 ============================================
# ======================================== 初始化配置 ==========================================
time.sleep(3)
print("FreakStudio: Using MPR121 capacitive touch keypad driver...")
# 初始化 I2C 总线
i2c = I2C(0, scl=Pin(5), sda=Pin(4), freq=400000)
# 扫描 I2C 总线
print("Scanning I2C bus...")
devices = i2c.scan()
if len(devices) == 0:
raise RuntimeError("No I2C device found")
print("Found %d device(s): %s" % (len(devices), [hex(d) for d in devices]))
# 检查目标设备地址
if MPR121_I2C_ADDR not in devices:
raise RuntimeError("Device not found at expected address 0x%02X" % MPR121_I2C_ADDR)
print("MPR121 found at address 0x%02X" % MPR121_I2C_ADDR)
# 初始化 MPR121 驱动
mpr121 = MPR121(i2c, address=MPR121_I2C_ADDR)
print("MPR121 initialized successfully")
# ======================================== 主程序 ===========================================
try:
while True:
current_time = time.ticks_ms()
if time.ticks_diff(current_time, last_print_time) >= print_interval:
# 读取 12 位触摸状态
touch_status = mpr121.touched()
print("Touch status: 0x%03X" % touch_status)
# 检查每个电极的触摸状态
touched_electrodes = []
for i in range(12):
if mpr121.is_touched(i):
touched_electrodes.append(i)
if len(touched_electrodes) > 0:
print(" Touched electrodes: %s" % str(touched_electrodes))
else:
print(" No electrode touched")
last_print_time = current_time
# 高频数据读取函数,注释默认执行,可 REPL 手动调用
# print_all_filtered_data()
# print_all_baseline_data()
# 模式切换函数,注释默认执行,可 REPL 手动触发
# test_threshold_config()
# 边界参数测试,注释默认执行,可 REPL 手动触发
# test_boundary_parameters()
# 异常参数测试,注释默认执行,可 REPL 手动触发
# test_invalid_parameters()
time.sleep_ms(10)
except KeyboardInterrupt:
print("Program interrupted by user")
except OSError as e:
print("Hardware communication error: %s" % str(e))
except Exception as e:
print("Unknown error: %s" % str(e))
finally:
print("Cleaning up resources...")
mpr121.deinit()
del mpr121
print("Program exited")
注意事项
| 类别 | 说明 |
|---|---|
| 工作条件 | 工作电压:3.3V;I2C 时钟频率:最高 400kHz |
| I2C 地址 | 默认地址:0x5A(可通过硬件 ADDR 引脚配置为 0x5A-0x5D) |
| 电极范围 | 支持 12 个电极通道(编号 0-11) |
| 阈值范围 | 触摸/释放阈值:0-255 |
| 使用限制 | 修改阈值时驱动会临时进入停止模式,期间触摸检测暂停 |
| 兼容性 | 适用于所有支持 I2C 的 MicroPython 开发板 |
版本记录
| 版本号 | 日期 | 作者 | 修改说明 |
|---|---|---|---|
| v1.0.0 | 2026-04-26 | Mike Causer | 初始版本,支持 12 通道触摸检测、阈值配置、数据读取 |
联系方式
- 作者:Mike Causer
- GitHub:https://github.com/mcauser/micropython-mpr121
许可协议
MIT License
Copyright (c) 2018 Mike Causer
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 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 THE SOFTWARE.