diff --git a/libraries/ADXL346/README-zh.md b/libraries/ADXL346/README-zh.md deleted file mode 100644 index 1da35b1..0000000 --- a/libraries/ADXL346/README-zh.md +++ /dev/null @@ -1,167 +0,0 @@ -# adxl346 - -默认初始化2G量程。 - -**类引用:** - -```python -from adxl346 import Adxl346 -``` - - - -**实例化参数:** - -| 名称 | 必填 | 类型 | 说明 | -| -------- | ---- | ------- | ----------------------------------- | -| i2c | 是 | i2c对象 | 如I2C(I2C.I2C1, I2C.STANDARD_MODE) | -| dev_addr | 否 | int | 默认0x53 | - -```python -i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) -adxl = Adxl346(i2c_dev) -``` - -**接口函数:** - -l **set_range(range=0)** - -设置量程。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| range | 否 | int | range_2g:0;
range_4g :1;
range_8g :2;
range_16g:3 | - -返回值: - -​ 无。 - -l **int_enable(int_code,tap_thr,dur,tap_axis,laten,window,ff_thr,ff_time,act_thr,act_axis,inact_thr,inact_axis,inact_time)** - -​ 中断使能。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ---------- | ---- | ---- | ------------------------------------------------------------ | -| int_code | 是 | int | 中断类型
单击中断:0x40
双击中断:0x20
运动中断:0x10
静止中断:0x08
自由落体中断:0x04 | -| tap_thr | 否 | int | 单双击中断选配
敲击中断阈值,默认0x30,建议不要小于该值 | -| dur | 否 | int | 单双击中断选配
敲击期间,默认0x20,建议大于0x10 | -| tap_axis | 否 | int | 单双击中断选配
敲击轴,默认0x07,既xyz,
只x轴:0x04
只y轴:0x02
只z轴:0x01 | -| laten | 否 | int | 双击中断选配
延迟,双击需在单击检测后该段时间外触发,默认0x15 | -| window | 否 | int | 双击中断选配
窗口,双击需在该时间内完成,默认0xff | -| ff_thr | 否 | int | 自由落体中断选配
加速度阈值,触发需大于该加速度,默认0x06,建议3-9 | -| ff_time | 否 | int | 自由落体中断选配
加速度时间,触发需大于该时间,默认0x15,建议0x14-0x46 | -| act_thr | 否 | int | 运动中断选配
加速度阈值,触发需大于该加速度,默认0x03 | -| act_axis | 否 | int | 运动中断选配,运动轴,默认0xf0
只x轴:0xc0
只y轴:0xa0
只z轴:0x90 | -| inact_thr | 否 | int | 静止中断选配
加速度阈值,触发需大于该加速度,默认0x03 | -| inact_axis | 否 | int | 静止中断选配,运动轴,默认0x0f
只x轴:0x0c
只y轴:0x0a
只z轴:0x09 | -| inact_time | 否 | int | 静止中断选配
静止保持时间,触发需静止大于该时间,默认0x03 | - -返回值: - -​ 0 :成功 - -​ -1 : 失败 - -l **clear_int(int_code)** - -​ 清除某中断使能。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| -------- | ---- | ---- | ------------------------------------------------------------ | -| int_code | 是 | int | 中断类型
单击中断:0x40
双击中断:0x20
运动中断:0x10
静止中断:0x08
自由落体中断:0x04 | - -返回值: - -​ 无 - -l **read_acceleration()** - -​ 读取三轴加速度。 - -参数: - -​ 无。 - -返回值: - -| 名称 | 类型 | 说明 | -| ------- | ----- | --------------------- | -| (x,y,z) | tuple | x, y, z轴加速度,单位G | - - - -l **process_single_tap ()** - -​ 循环读取中断源寄存器,单击中断检测。 - -​ 注:未检测到中断则死循环,谨慎在主线程执行,执行前请确保单击中断使能并配置正确。 - -参数: - -​ 无。 - -返回值: - -​ 1:检测到单击中断 - -l **process_double_tap()** - -​ 循环读取中断源寄存器,双击中断检测。 - -​ 注:未检测到中断则死循环,谨慎在主线程执行,执行前请确保双击中断使能并配置正确。 - -参数: - -​ 无。 - -返回值: - -​ 1:检测到双击中断 - -l **process_act ()** - -​ 循环读取中断源寄存器,运动中断检测。 - -​ 注:未检测到中断则死循环,谨慎在主线程执行,执行前请确保运动中断使能并配置正确。 - -参数: - -​ 无。 - -返回值: - -​ 1:检测到运动中断 - -l **process_inact()** - -​ 循环读取中断源寄存器,静止中断检测。 - -​ 注:未检测到中断则死循环,谨慎在主线程执行,执行前请确保静止中断使能并配置正确。 - -参数: - -​ 无。 - -返回值: - -​ 1:检测到静止中断 - -l **process_ff ()** - -​ 循环读取中断源寄存器,自由落体中断检测。 - -​ 注:未检测到中断则死循环,谨慎在主线程执行,执行前请确保自由落体中断使能并配置正确。 - -参数: - -​ 无。 - -返回值: - -​ 1:检测到自由落体中断 diff --git a/libraries/ADXL346/README.md b/libraries/ADXL346/README.md index 7d16a50..42f2318 100644 --- a/libraries/ADXL346/README.md +++ b/libraries/ADXL346/README.md @@ -1,182 +1,212 @@ -# adxl346 +# ADXL346 Three-Axis Acceleration Sensor Driver Documentation +## Overview +This document explains how to use the ADXL346 three-axis acceleration sensor driver module to read the motion data of the device via the I2C interface, including the values of the three-axis acceleration and the ability to configure various motion detection interrupts. -Default initialization for a 2G range. +## Main Features -**Class Reference:** +- Read the acceleration values of X/Y/Z axes +- Set the measurement range (2g/4g/8g/16g) +- Configure 5 types of motion detection interrupts: + - Single click (Single tap) + - Double click (Double tap) + - Activity detection (Activity) + - Inactivity detection (Inactivity) + - Free-fall (Free-fall) +- Real-time interrupt status detection +## Quick Start +### 1. Import Required Modules ```python +from machine import I2C from adxl346 import Adxl346 +import utime ``` - - - - - -**Instantiation Parameters:** - -| Name | Required | Type | Description | -| -------- | ---- | ------- | ----------------------------------- | -| I2C | Yes | I2C object | Such as I2C(I2C.I2C1, I2C.STANDARD_MODE) | -| Device address | No | int | Default: 0x53 | +### 2. Initialize the sensors ```python +# Initialize the ADXL346 sensor on the I2C1 bus, with the device address set to 0x53 i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) -adxl = Adxl346(i2c_dev) +accel_sensor = Adxl346(i2c_dev) ``` -**Interface Function:** - -l **set_range(range=0)** - - -Set the range. - -Parameters: - -| Name | Required | Type | Description | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| range | No | int | range_2g: 0;
range_4g : 1;
range_8g : 2;
range_16g: 3 | - -Return value: - -No. - -l **int_enable(int_code,tap_thr,dur,tap_axis,laten,window,ff_thr,ff_time,act_thr,act_axis,inact_thr,inact_axis,inact_time)** - - -Interrupt enable. - -Parameters: +### 3. Set the measurement range -| Name | Required | Type | Description | -| ---------- | ---- | ---- | ------------------------------------------------------------ | -| int_code | Yes | int | Interrupt type
Single-click interrupt: 0x40
Double-click interrupt: 0x20
Motion interrupt: 0x10
Stationary interrupt: 0x08
Free fall interrupt: 0x04 | -| tap_thr | No | int | Optional for single or double click interrupts
Click threshold, default 0x30, recommended not to be less than this value | -| dur | No | int | Optional for single or double click interrupts
Click duration, default 0x20, recommended to be greater than 0x10 | -| tap_axis | No | int | Optional for single or double click interrupts
Click axis, default 0x07, which is xyz
Only x-axis: 0x04
Only y-axis: 0x02
Only z-axis: 0x01 | -| laten | No | int | Optional for double click interrupts
Delay, double click needs to be triggered after the single click detection for this period, default 0x15 | -| window | No | int | Optional for double click interrupts
Window, double click needs to be completed within this time, default 0xff | -| ff_thr | No | int | Optional for free fall interrupt
Acceleration threshold, trigger needs to be greater than this acceleration, default 0x06, recommended 3-9 | -| ff_time | No | int | Optional for free fall interrupt
Acceleration time, trigger needs to be greater than this time, default 0x15, recommended 0x14-0x46 | -| act_thr | No | int | Optional for motion interrupt
Acceleration threshold, trigger needs to be greater than this acceleration, default 0x03 | -| act_axis | No | int | Optional for motion interrupt, motion axis, default 0xf0
Only x-axis: 0xc0
Only y-axis: 0xa0
Only z-axis: 0x90 | -| inact_thr | No | int | Optional for stationary interrupt
Acceleration threshold, trigger needs to be greater than this acceleration, default 0x03 | -| inact_axis | No | int | Optional for stationary interrupt, motion axis, default 0x0f
Only x-axis: 0x0c
Only y-axis: 0x0a
Only z-axis: 0x09 | -| inact_time | No | int | Optional for stationary interrupt
Stationary duration, trigger needs to be stationary for more than this time, default 0x03 | +```python +# Set the range (optional: 2g/4g/8g/16g) +accel_sensor.set_range(Adxl346.range_8g) # Set to 8g range +``` -Return value: -0 : Success +### 4. Read sensor data +#### Read the values of the three-axis acceleration --1 : Failure +```python +x, y, z = accel_sensor.read_acceleration() +print("Acceleration values: X={}g, Y={}g, Z={}g".format(x, y, z)) +``` -l **clear_int(int_code)** +Configure and use interrupts (taking double-click detection as an example) -Clear the enable of a certain interrupt. +```python +# Enable Double-click Detection Interruption +accel_sensor.int_enable(Adxl346.DOUB_TAP_INT) -Parameters: +# Wait for and handle interrupt events +accel_sensor.process_double_tap() +print("Detecting double-click event!" ) -| Name | Required | Type | Description | -| -------- | ---- | ---- | ------------------------------------------------------------ | -| int_code | Yes | int | Interrupt type
Single-click interrupt: 0x40
Double-click interrupt: 0x20
Motion interrupt: 0x10
Stationary interrupt: 0x08
Free fall interrupt: 0x04 | +# Read the current acceleration value +x, y, z = accel_sensor.read_acceleration() +``` -Return value: +## API Interface Description -No +### **`Adxl346(i2c, dev_addr=0x53)`** -l **read_acceleration()** +Construct the constructor and initialize the ADXL346 sensor. +**Parameter Description:** -Read the three-axis acceleration. -Parameters: +- i2c: I2C device instance +- dev_addr: Sensor I2C address (default 0x53) -No. +### **`set_range(range=range_2g)`** -Return value: -| Name | Type | Description | -| ------- | ----- | --------------------- | -|(x, y, z) | tuple | Axial accelerations along the x, y, and z axes, in units of G | +Set the acceleration measurement range. +**Parameter Explanation:** +- range: Range selection (range_2g, range_4g, range_8g, range_16g) +### **`read_acceleration()`** -l **process_single_tap ()** +Read the values of the three-axis acceleration. -Loop through reading the interrupt source register and click on interrupt detection. +**Return Value: ** -Note: If no interruption is detected, it will result in an infinite loop. It is recommended to execute it in the main thread with caution. Before execution, make sure to enable the interruption and configure it correctly. +- (x, y, z) Three-axis acceleration values, with units of g -Parameters: +### **`int_enable(int_code, **kwargs)`** -No. -Return value: +Enable the specific interrupt function. -Detected a click interruption +**Parameter Explanation:** -l **process_double_tap()** +- int_code: Interrupt Type Selection: + - SING_TAP_INT: Single Click + - DOUB_TAP_INT: Double Click + - ACT_INT: Activity Detection + - INACT_INT: Inactivity Detection + - FF_INT: Free Fall +- kwargs: Interrupt Parameters (refer to the technical description) +### Interrupt handling function. -Loop through reading the interrupt source register, and double-click the interrupt detection. +Wait for a specific interrupt to occur: -Note: If no interruption is detected, it will result in an infinite loop. It is recommended to execute it in the main thread with caution. Before execution, make sure to enable the interrupt function and configure it correctly by double-clicking. +- process_single_tap(): Single click +- process_double_tap(): Double click +- process_act(): Activity detection +- process_inact(): Inactivity detection +- process_ff(): Free fall -Parameters: +## Application Examples -No. +Basic data reading -Return value: +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +adxl = Adxl346(i2c_dev) +adxl.set_range(Adxl346.range_8g) -Detected double-click interruption -l **process_act ()** +while True: + x, y, z = adxl.read_acceleration() + print("X={:.3f}g, Y={:.3f}g, Z={:.3f}g".format(x, y, z)) + utime.sleep(1) +``` -Loop through reading the interrupt source register and perform motion interrupt detection. +Double-click detection application +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +adxl = Adxl346(i2c_dev) +adxl.int_enable(Adxl346.DOUB_TAP_INT) -Note: If no interruption is detected, it will result in an infinite loop. It is recommended to execute it in the main thread with caution. Before execution, make sure that the motion interruption is enabled and configured correctly. -Parameters: +while True: + # Waiting for double-click event + adxl.process_double_tap() -No. + # After the incident occurred, data was + read. x, y, z = adxl.read_acceleration() + print("Double-click event! Current acceleration: X={}g, Y={}g, Z={}g".format(x, y, z)) +``` -Return value: -Motion interruption has been detected. +Free fall detection +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +adxl = Adxl346(i2c_dev) +adxl.int_enable(Adxl346.FF_INT, ff_thr=0x06, ff_time=0x15) -l **process_inact()** +while True: + if adxl.process_ff(): + printf("Detecting free fall event!" ) +``` -Loop through reading the interrupt source register and perform static interrupt detection. +## Technical Description +### 1. Range and Resolution -Note: If no interruption is detected, it will result in an infinite loop. It is recommended to execute it in the main thread with caution. Before execution, make sure that the interrupt enable is enabled and the configuration is correct. +| Range | Resolution | Maximum Measurement Value | |----|----|----| +|2g |0.004g| ±2g| +|4g |0.008g| ±4g| +|8g |0.016g| ±8g| +|16g |0.032g| ±16g| +### 2. Interruption Parameter Configuration -Parameters: +Each interrupt type supports the following parameters: +- Single click/double click: + - tap_thr: Trigger threshold (default 0x30) + - dur: Duration (default 0x20) + - tap_axis: Detection axis (default 0x07 for all axes) -No. +- Free fall: -Return value: + - ff_thr: Trigger threshold (default: 0x06) + - ff_time: Time window (default: 0x15) -Detected a static interruption +- Activity Detection: -l **process_ff ()** + - act_thr: Trigger threshold (default: 0x03) + - act_axis: Detection axis (default: 0xF0) +- Static detection: -Loop through reading the interrupt source register and detect free-fall interrupts. + - inact_thr: Trigger threshold (default: 0x03) + - inact_axis: Detection axis (default: 0x0F) + - inact_time: Duration of inactivity (default: 3) -Note: If no interruption is detected, it will result in an infinite loop. It is recommended to execute it in the main thread with caution. Before execution, make sure that the free fall interruption is enabled and configured correctly. +### 3. Interruption Response Characteristics -Parameters: +- All interruption detection response times are at the millisecond level. +- It is recommended to retain a delay of at least 20ms in the main loop (utime.sleep_ms(20)). +- In actual applications, the detection threshold parameters should be adjusted according to the requirements. -No. +Common Issues Troubleshooting -Return value: +- Check the I2C wiring and address (default 0x53) +- Ensure the sensor is properly powered (3.3V) +- Confirm that the interrupt pin is correctly connected and configured +- Confirm that there is no address conflict on the I2C bus -1: Detected a break in free fall \ No newline at end of file +This driver provides a complete interface for motion detection applications using the ADXL346 acceleration sensor, and is applicable to scenarios such as posture detection, impact detection, and free fall detection. \ No newline at end of file diff --git a/libraries/ADXL346/README_zh.md b/libraries/ADXL346/README_zh.md new file mode 100644 index 0000000..f4f4e2f --- /dev/null +++ b/libraries/ADXL346/README_zh.md @@ -0,0 +1,200 @@ +# ADXL346三轴加速度传感器驱动文档 +## 概述 + +本文档介绍如何使用ADXL346三轴加速度传感器驱动模块,通过I2C接口读取设备的运动数据,包括三轴加速度值及配置多种运动检测中断。 + +## 主要特性 + +- 读取X/Y/Z三轴加速度值 +- 设置测量量程(2g/4g/8g/16g) +- 配置5种运动检测中断: + - 单次点击(Single tap) + - 双击(Double tap) + - 活动检测(Activity) + - 静止检测(Inactivity) + - 自由落体(Free-fall) +- 实时中断状态检测 + +## 快速入门 +### 1. 导入所需模块 +```python +from machine import I2C +from adxl346 import Adxl346 +import utime +``` +### 2. 初始化传感器 + +```python +# 在I2C1总线上初始化ADXL346传感器,设备地址0x53 +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +accel_sensor = Adxl346(i2c_dev) +``` + +### 3. 设置测量量程 + +```python +# 设置量程(可选2g/4g/8g/16g) +accel_sensor.set_range(Adxl346.range_8g) # 8g量程 +``` + +### 4. 读取传感器数据 +#### 读取三轴加速度值 + +```python +x, y, z = accel_sensor.read_acceleration() +print("加速度值: X={}g, Y={}g, Z={}g".format(x, y, z)) +``` + +#### 配置并使用中断(以双击检测为例) + +```python +# 启用双击检测中断 +accel_sensor.int_enable(Adxl346.DOUB_TAP_INT) + +# 等待并处理中断事件 +accel_sensor.process_double_tap() +print("检测到双击事件!") + +# 读取当前加速度值 +x, y, z = accel_sensor.read_acceleration() +``` + +## API接口说明 + +### **`Adxl346(i2c, dev_addr=0x53)`** + +构造函数,初始化ADXL346传感器。 + +​​**参数说明:** + +- i2c: I2C设备实例 +- dev_addr: 传感器I2C地址(默认0x53) + +### **`set_range(range=range_2g)`** + +设置加速度测量量程。 + +​**​参数说明:​​** + +- range: 量程选择(range_2g, range_4g, range_8g, range_16g) + +### **`read_acceleration()`** + +读取三轴加速度值。 + +​**​返回值:​​** + +- (x, y, z) 三轴加速度值,单位为g + +### **`int_enable(int_code, **kwargs)`** + +启用特定中断功能。 + +​**​参数说明:​**​ + +- int_code: 中断类型选择: + - SING_TAP_INT: 单次点击 + - DOUB_TAP_INT: 双击 + - ACT_INT: 活动检测 + - INACT_INT: 静止检测 + - FF_INT: 自由落体 +- kwargs: 中断参数(详见技术说明) + +### 中断处理函数。 + +阻塞等待特定中断发生: + +- process_single_tap(): 单次点击 +- process_double_tap(): 双击 +- process_act(): 活动检测 +- process_inact(): 静止检测 +- process_ff(): 自由落体 + +## 应用示例 + +基本数据读取 + +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +adxl = Adxl346(i2c_dev) +adxl.set_range(Adxl346.range_8g) + +while True: + x, y, z = adxl.read_acceleration() + print("X={:.3f}g, Y={:.3f}g, Z={:.3f}g".format(x, y, z)) + utime.sleep(1) +``` + +双击检测应用 +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +adxl = Adxl346(i2c_dev) +adxl.int_enable(Adxl346.DOUB_TAP_INT) + +while True: + # 等待双击事件 + adxl.process_double_tap() + + # 事件发生后读取数据 + x, y, z = adxl.read_acceleration() + print("双击事件!当前加速度: X={}g, Y={}g, Z={}g".format(x, y, z)) +``` + +自由落体检测 +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +adxl = Adxl346(i2c_dev) +adxl.int_enable(Adxl346.FF_INT, ff_thr=0x06, ff_time=0x15) + +while True: + if adxl.process_ff(): + print("检测到自由落体事件!") +``` + +## 技术说明 +### 1. 量程与分辨率 + +|量程|分辨率|最大测量值| +|----|----|----| +|2g |0.004g|±2g| +|4g|0.008g|±4g| +|8g|0.016g| ±8g| +|16g|0.032g|±16g| +### 2. 中断参数配置 + +各中断类型支持以下参数: +- 单次点击/双击:​​ + - tap_thr: 触发阈值(默认0x30) + - dur: 持续时间(默认0x20) + - tap_axis: 检测轴(默认0x07所有轴) + +- ​自由落体:​​ + + - ff_thr: 触发阈值(默认0x06) + - ff_time: 时间窗口(默认0x15) + +- ​活动检测:​​ + + - act_thr: 触发阈值(默认0x03) + - act_axis: 检测轴(默认0xF0) + +- ​静止检测:​​ + + - inact_thr: 触发阈值(默认0x03) + - inact_axis: 检测轴(默认0x0F) + - inact_time: 静止时长(默认3) + +### 3. 中断响应特性 + +- 所有中断检测响应时间均在毫秒级 +- 建议主循环中至少保留20ms延时(utime.sleep_ms(20)) +- 实际应用中应根据需求调整各检测阈值参数 + +常见问题排查 + +- 检查I2C接线和地址(默认0x53) +- 确保传感器正确供电(3.3V) +- 确认中断引脚已正确连接和配置 +- 确认I2C总线上无地址冲突 + +本驱动为使用ADXL346加速度传感器的运动检测应用提供了完整接口,适用于姿态检测、冲击检测、自由落体检测等应用场景。 \ No newline at end of file diff --git a/libraries/AW9523B/README-zh.md b/libraries/AW9523B/README-zh.md deleted file mode 100644 index 86f312f..0000000 --- a/libraries/AW9523B/README-zh.md +++ /dev/null @@ -1,89 +0,0 @@ -# AW9523 GPIO扩展器驱动模块 - -**类引用:** -```python -from aw9523 import AW9523 -``` - -**实例化参数:** - -|名称| 必填| 类型| 说明| -|----|----|----|----| -|i2c_bus| 是| I2C对象| I2C总线对象| -|int_pin| 否| int| 中断引脚号,默认1| -|int_mode| 否| int| 中断模式,默认0| -|int_callback| 否| function| 中断回调函数| -|address| 否| int| I2C设备地址,默认0x58(按键驱动地址)| - -**端口对象:** -```python -porta = Port(0, aw) # 端口A -portb = Port(1, aw) # 端口B -``` - -**端口属性:** - -|属性| 类型| 说明| -|----|----|----| -|mode| int| 端口模式(0=输出,1=输入)| -|interrupt_enable| int| 中断使能| -|interrupt_flag| int| 中断标志(只读)| -|gpio| int| GPIO值| - -**主要方法:** - -l reset() - -复位AW9523芯片。 - -​​参数:​​ - -无 - -​​返回值:​​ - -无 - -l pin(pin, mode=None, value=None, interrupt_enable=None) - -配置单个引脚。 - -​​参数:​​ - -|名称 |类型| 说明| -|----|----|----| -|pin| int| 引脚号(0-15)| -|mode| int| 模式:0=输出,1=输入| -|value| int| 输出值:0=低电平,1=高电平| -|interrupt_enable| int| 中断使能:0=禁用,1=启用| - -​​返回值:​​ - -设置值时:无 - -读取值时:当前引脚电平(0或1) - -l read(pin) - -读取单个引脚电平。 - -​​参数:​​ - -|名称| 类型| 说明| -|----|----|----| -|pin| int| 引脚号(0-15)| - -​​返回值:​​ - -0:低电平 - -1:高电平 - -**全局属性:** - -|属性| 类型| 说明| -|----|----|----| -|mode| int| 所有引脚模式(读写)| -|interrupt_enable| int|所有引脚中断使能(读写)| -|interrupt_flag |int| 所有引脚中断标志(只读)| -|gpio| int| 所有GPIO值(读写)| \ No newline at end of file diff --git a/libraries/AW9523B/README.md b/libraries/AW9523B/README.md index c9de6ee..cf9efbd 100644 --- a/libraries/AW9523B/README.md +++ b/libraries/AW9523B/README.md @@ -1,95 +1,224 @@ -# AW9523 GPIO Expansion Module Driver Module +# AW9523 GPIO Expansion Chip Driver Documentation +## Overview -**Class Reference:** +This document explains how to use the AW9523 driver module to achieve GPIO expansion functionality. This chip expands 16 bidirectional GPIO pins through the I2C interface, supports independent configuration of input/output modes, and has a level change interrupt detection function. + +## Main Features +- Supports 16 bidirectional GPIO pins expansion +- Allows independent configuration of each pin as input/output mode +- Supports high/low level control (output mode) +- Supports pin status reading (input mode) +- Built-in edge detection function (rising/falling edge) +- Real-time callback notification of interrupt status + +## Quick Start + +### 1. Import Required Modules ```python +from machine import I2C, ExtInt from aw9523 import AW9523 +from usr.common import create_thread +import utime ``` -**Instantiation Parameters:** +### 2. Initialize the sensors +```python +# Create an instance of the I2C device (I2C1, standard mode) +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) + +# Define the interrupt callback function +def int_callback(pin_data): + pin, level = pin_data + print("Pin {} has a level change! Current level: {}".format(pin, 'High' if level else 'Low')) + +# Initialize the AW9523 chip on the I2C0 bus (address 0x58, using pin 1 as the interrupt pin) +expander = AW9523( + i2c_bus=i2c_dev, + int_pin = 1, # Interrupt pin number + int_callback = int_callback # Interrupt callback function + ) +``` -| Name | Required | Type | Description | -|----|----|----|----| -|i2c_bus| Yes | I2C object | I2C bus object | -|int_pin| No | int | Interrupt pin number, default 1 | -|int_mode| No | int | Interrupt mode, default 0 | -|int_callback| No | function | Interrupt callback function | -|address| No | int | I2C device address, default 0x58 (keypad driver address) | -**Port Object:** ```python -porta = Port(0, aw) # Port A -portb = Port(1, aw) # Port B ``` +### 3. Configure GPIO pins +```python +# Set pin 0 to output mode and set it to high level +expander.pin(0, mode=0, value=1) +# Set pin 8 to input mode and enable interrupts +expander.pin(8, mode=1, interrupt_enable=1) -**Port Attributes:** +# Set pin 9 to input mode and disable interrupts +expander.pin(9, mode=1, interrupt_enable=0) +``` -| Attribute | Type | Description | -|----|----|----| -|mode| int| Port mode (0 = output, 1 = input)| -|interrupt_enable| int| Interrupt enable| -|interrupt_flag| int| Interrupt flag (read-only)| -|gpio| int| GPIO value| -**Main Method:** +### 4. Read the pin status +```python +# Read the current level state of pin 8 +level = expander.read(8) +print("Pin 8 current level: ".format('High' if level else 'Low')) -l reset() +# Read the status of all pins in batches +all_pins_state = expander.gpio +print("All pin states: {}".format(bin(all_pins_state))) +``` +## API Interface Description -Reset the AW9523 chip. +### **`AW9523(i2c_bus, int_pin=1, int_mode=0, int_callback=None, address=0x58)`** -Parameters: -No +Constructor, initializing the AW9523 chip +**Parameter Description:** -Return value: -No +- i2c_bus: I2C bus instance +- int_pin: Interrupt detection pin number +- int_mode: Interrupt triggering mode +- int_callback: Interrupt callback function +- address: Device I2C address (0x58 or 0x5B) +**`pin(pin, mode=None, value=None, interrupt_enable=None)`** -l pin(pin, mode=None, value=None, interrupt_enable=None) +Configure the specified pin parameters -Configure a single pin. +**Parameter Explanation:** -Parameters: -| Name | Type | Description | -|----|----|----| -|pin| int| Pin number (0-15)| -|mode| int| Mode: 0 = Output, 1 = Input| -|value| int| Output value: 0 = Low level, 1 = High level| -|interrupt_enable| int| Interrupt enable: 0 = Disable, 1 = Enable| +- pin: Pin number (0-15) +- mode: Pin mode + - 0: Output mode + - 1: Input mode +- value: Output level value (valid in output mode) + - 0: Low level + - 1: High level +- interrupt_enable: Interrupt enable + - 0: Disable interrupt + - 1: Enable interrupt -Return value: +**`read(pin)`** -When setting the value: None -When reading the value: Current pin level (0 or 1) +Read the level status of the specified pin -l read(pin) +**Parameter Explanation:** -Read the level of a single pin. +- pin: Pin number (0-15) -Parameters: +- Return value: -| Name | Type | Description | -|----|----|----| -| pin | int | Pin number (0-15) | + - 0: Low level + - 1: High level + +Attribute accessor -Return value: +- mode: All pin mode status (16 bits) +- interrupt_enable: All pin interrupt enable status (16 bits) +- gpio: All pin level status (16 bits) + +## Application Example +Basic GPIO Expansion Application +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +expander = AW9523(i2c_dev) -0: Low voltage level +# Set pins 0 to 3 to output mode +for i in range(4): + expander.pin(i, mode=0, value=0) -High level +# Set pins 8 to 11 to input mode +for i in range(8, 12): + expander.pin(i, mode=1, interrupt_enable=0) + +while True: + # Read the status of pins 8 to 1 + for i in range(8, 12): + state = expander.read(i) + print("Pin {i} state: {state}".format(i, state)) + + utime.sleep(1) +``` +Interrupt detection application +```python +def int_handler(pin_data): + pin, level = pin_data + print("Pin {} changed to {}".format(pin, level)) -**Global Attribute:** +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +expander = AW9523(i2c_dev, int_callback=int_handler) -| Attribute | Type | Description | + +# Set pins 4 to 7 as inputs and enable interrupts +for i in range(4, 8): + expander.pin(i, mode=1, interrupt_enable=1) + +# Continuously perform other tasks +while True: + # Main Program Logic + utime.sleep(10) +``` +LED Control Application + +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +expander = AW9523(i2c_dev) + +# Set pins 12 to 15 to output mode to control the +LED led_pins = [12, 13, 14, 15] +for pin in led_pins: + expander.pin(pin, mode=0, value=0) + +# LED Waterfall Light Effect while True: +for pin in led_pins: + expander.pin(pin, value=1) # Turn on the LED + utime.sleep_ms(200) + expander.pin(pin, value=0) # Turn off the LED +``` + +## Technical Description +### 1. Pin Mapping + +|Port|Pin Range|Register| +|----|----|----| +|PORTA|0-7|0x00| +|PORTB|8-15|0x01| + + +### 2. Interruption Handling Mechanism + +- Interrupt triggered by using the hardware INT pin +- Interrupt triggered when the level changes +- Interrupt callback function format: callback([pin, level]) + - pin: Pin number that has changed (0-15) + - level: Changed level (0: low/1: high) + +### 3. Configuration Options +| Configuration Type | Value Range | Description | |----|----|----| -|mode| int| All pin modes (read/write)| -|interrupt_enable| int| All pin interrupt enable (read/write)| -|interrupt_flag |int| All pin interrupt flags (read-only)| -|gpio| int| All GPIO values (read/write)| \ No newline at end of file +| Pin Mode | 0/1 | 0 = Output, 1 = Input | +| Output Level | 0/1 | 0 = Low Level, 1 = High Level | +| Interrupt Enable | 0/1 | 0 = Disable, 1 = Enable | +| Interrupt Trigger Mode | 0/1 | 0 = Bi-directional Edge, 1 = Unidirectional Edge (Reserved) | + +### 4. I2C Address Explanation +| Device Type | I2C Address | + |----|----| +|Button Driver|0x58| +|IO Expander|0x5B| + +Common Issues Troubleshooting +- Check if the I2C connections are correct. +- Confirm if the I2C address is correct (0x58 or 0x5B). +- Ensure that the interrupt_enable is set to 1. +- Verify if the INT pin configuration is correct. +- Make sure there are no blocking operations on the interrupt line within the loop. + + + +This driver provides a complete control interface for the AW9523 GPIO expansion chip, and is suitable for various scenarios that require IO expansion. \ No newline at end of file diff --git a/libraries/AW9523B/README_zh.md b/libraries/AW9523B/README_zh.md new file mode 100644 index 0000000..9aa334d --- /dev/null +++ b/libraries/AW9523B/README_zh.md @@ -0,0 +1,212 @@ +# AW9523 GPIO扩展芯片驱动文档 +## 概述 + +本文档介绍如何使用AW9523驱动模块实现GPIO扩展功能。该芯片通过I2C接口扩展16个双向GPIO引脚,支持独立配置输入/输出模式,并具备电平变化中断检测功能。 + +## 主要特性 +- 扩展16个双向GPIO引脚 +- 独立配置每个引脚为输入/输出模式 +- 支持高低电平控制(输出模式) +- 支持引脚状态读取(输入模式) +- 内置边沿中断检测功能(上升沿/下降沿) +- 中断状态实时回调通知 + +## 快速入门 +### 1. 导入所需模块 + +```python +from machine import I2C, ExtInt +from aw9523 import AW9523 +from usr.common import create_thread +import utime +``` + +### 2. 初始化传感器 +```python +# 创建I2C设备实例(I2C1,标准模式) +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) + +# 定义中断回调函数 +def int_callback(pin_data): + pin, level = pin_data + print("引脚{}电平变化! 当前电平: {'高' if level else '低'}".format(pin)) + +# 在I2C0总线上初始化AW9523芯片(地址0x58,使用引脚1作为中断引脚) +expander = AW9523( + i2c_bus=i2c_dev, + int_pin=1, # 中断引脚编号 + int_callback=int_callback # 中断回调函数 +) +``` + +### 3. 配置GPIO引脚 +```python +# 配置引脚0为输出模式,并设置高电平 +expander.pin(0, mode=0, value=1) + +# 配置引脚8为输入模式,并启用中断 +expander.pin(8, mode=1, interrupt_enable=1) + +# 配置引脚9为输入模式,不启用中断 +expander.pin(9, mode=1, interrupt_enable=0) +``` + +### 4. 读取引脚状态 +```python +# 读取引脚8的当前电平状态 +level = expander.read(8) +print("引脚8当前电平: {}".format('高' if level else '低')) + +# 批量读取所有引脚状态 +all_pins_state = expander.gpio +print("所有引脚状态: {}".format(bin(all_pins_state))) +``` + +## API接口说明 + +### **`AW9523(i2c_bus, int_pin=1, int_mode=0, int_callback=None, address=0x58)`** + +构造函数,初始化AW9523芯片 + +​**​参数说明:​​** + +- i2c_bus: I2C总线实例 +- int_pin: 中断检测引脚编号 +- int_mode: 中断触发模式 +- int_callback: 中断回调函数 +- address: 设备I2C地址(0x58或0x5B) + +**`pin(pin, mode=None, value=None, interrupt_enable=None)`** + +配置指定引脚参数 + +​​**参数说明:** + +- pin: 引脚编号 (0-15) +- mode: 引脚模式 + - 0: 输出模式 + - 1: 输入模式 +- value: 输出电平值(输出模式时有效) + - 0: 低电平 + - 1: 高电平 +- interrupt_enable: 中断使能 + - 0: 禁用中断 + - 1: 使能中断 + +**`read(pin)`** + +读取指定引脚电平状态 + +**​参数说明:** + +- pin: 引脚编号 (0-15) + +**​​返回值:​​** + + - 0: 低电平 + - 1: 高电平 + +属性访问器 + +- mode: 所有引脚模式状态(16位) +- interrupt_enable: 所有引脚中断使能状态(16位) +- gpio: 所有引脚电平状态(16位) + +## 应用示例 +基础GPIO扩展应用 +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +expander = AW9523(i2c_dev) + +# 配置引脚0-3为输出模式 +for i in range(4): + expander.pin(i, mode=0, value=0) + +# 配置引脚8-11为输入模式 +for i in range(8, 12): + expander.pin(i, mode=1, interrupt_enable=0) + +while True: + # 读取引脚8-11状态 + for i in range(8, 12): + state = expander.read(i) + print("Pin {} state: {}".format(i, state)) + + utime.sleep(1) +``` + +中断检测应用 +```python +def int_handler(pin_data): + pin, level = pin_data + print("Pin {} changed to {}".format(pin, level)) + +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +expander = AW9523(i2c_dev, int_callback=int_handler) + +# 配置引脚4-7为输入,启用中断 +for i in range(4, 8): + expander.pin(i, mode=1, interrupt_enable=1) + +# 持续执行其他任务 +while True: + # 主程序逻辑 + utime.sleep(10) +``` +LED控制应用 +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +expander = AW9523(i2c_dev) + +# 配置引脚12-15为输出模式,控制LED +led_pins = [12, 13, 14, 15] +for pin in led_pins: + expander.pin(pin, mode=0, value=0) + +# LED流水灯效果 +while True: + for pin in led_pins: + expander.pin(pin, value=1) # 点亮LED + utime.sleep_ms(200) + expander.pin(pin, value=0) # 熄灭LED +``` +## 技术说明 +### 1. 引脚映射 + +|端口|引脚范围|寄存器| +|----|----|----| +|PORTA|0-7|0x00| +|PORTB|8-15|0x01| + +### 2. 中断处理机制 + +- 中断使用硬件INT引脚触发 +- 电平变化时中断引脚触发 +- 中断回调函数格式:callback([pin, level]) + - pin: 发生变化的引脚号 (0-15) + - level: 变化后的电平 (0:低/1:高) + +### 3. 配置选项 +|配置类型|取值范围|说明| +|----|----|----| +|引脚模式|0/1|0=输出, 1=输入| +|输出电平|0/1|0=低电平, 1=高电平| +|中断使能|0/1|0=禁用, 1=使能| +|中断触发模式|0/1|0=双边沿, 1=单边沿(保留)| + +### 4. I2C地址说明 +|设备类型|I2C地址| +|----|----| +|按键驱动|0x58| +|IO扩展器|0x5B| + +常见问题排查 + +- 检查I2C连线是否正确 +- 确认I2C地址是否正确(0x58或0x5B) +- 确认interrupt_enable设置为1 +- 检查INT引脚配置是否正确 +- 确保在循环中没有阻塞中断线程的操作 + + +本驱动为AW9523 GPIO扩展芯片提供了完整的控制接口,适用于各种需要扩展IO的应用场景 \ No newline at end of file diff --git a/libraries/BH1750(GY-302)/README.md b/libraries/BH1750(GY-302)/README.md index 8704294..f909ff7 100644 --- a/libraries/BH1750(GY-302)/README.md +++ b/libraries/BH1750(GY-302)/README.md @@ -1,19 +1,16 @@ # BH1750(gy-302) - -**Class Reference:** +**类引用:** ```python from BH1750 import Bh1750 ``` + +**实例化参数:** - - -"Instantiation Parameters:" - -| Name | Required | Type | Description | +| 名称 | 必填 | 类型 | 说明 | | -------- | ---- | ------- | ---- | | I2C | Yes | I2C object | | | Device address | No | int | 0x23 | @@ -23,8 +20,7 @@ i2c_obj=I2C(I2C.I2C1,I2C.STANDARD_MODE) bh1750 = Bh1750(i2c_obj) ``` - -**Interface Function:** +**接口函数:** l **on(), off(), reset()** @@ -41,16 +37,13 @@ No. l **set_measure_mode(mode)** +​ 设置测量模式,持续测量或单次测量,不同精度。 -Set the measurement mode, for continuous measurement or single measurement, with different levels of accuracy. +参数: -Parameters: - -| Name | Required | Type | Description | +| 名称 | 必填 | 类型 | 说明 | | ---- | ---- | ---- | ------------------------------------------------------------ | -| Mode | No | int | Default: 0.5lx precision;
0x10: (1lx precision)
0x13: (0.5lx precision) | - -Return value: +| mode | 否 | int | 默认0.5lx精度;
0x10:(1lx精度)
0x13:(0.5lx精度) | No diff --git a/libraries/BH1750(GY-302)/README-zh.md b/libraries/BH1750(GY-302)/README_zh.md similarity index 100% rename from libraries/BH1750(GY-302)/README-zh.md rename to libraries/BH1750(GY-302)/README_zh.md diff --git a/libraries/ESP8266/README-zh.md b/libraries/ESP8266/README-zh.md deleted file mode 100644 index 33998eb..0000000 --- a/libraries/ESP8266/README-zh.md +++ /dev/null @@ -1,49 +0,0 @@ -# ESP8266 SLIP 网络接口模块 -**类引用** -```python -from esp8266 import Esp8266_ap -``` - -**实例化参数:** - -|名称 | 必填 |类型|说明| -|----|----|----|----| -|uart| 是| UART对象 |用于连接ESP8266的UART接口| - - -**接口函数:** - -l **set_ap(name=None, pwd=None, project_name='wifi_setap', project_version='1.0.0')** - -配置ESP8266模块的AP模式参数。 - -**​​参数:**​​ - -| 名称 | 必填 | 类型 | 说明 | -|----|----|----|----| -| name | 否 |str | WiFi网络名称| -| pwd | 否| str| WiFi密码| -| project_name| 否| str| 网络检查项目名称,默认'wifi_setap'| -|project_version |否 |str| 网络检查项目版本,默认'1.0.0'| - -​​返回值:​​ - -0:成功 - --1:失败 - -l **wifi_on()** - -启用ESP8266模块并配置SLIP网络接口 - -​​返回值:​​ - -0:成功 - --1:失败 - -l **wifi_off()** - -关闭ESP8266模块并释放资源 - -​​返回值:​​ 无 \ No newline at end of file diff --git a/libraries/ESP8266/README.md b/libraries/ESP8266/README.md index e5a1c93..05e2859 100644 --- a/libraries/ESP8266/README.md +++ b/libraries/ESP8266/README.md @@ -1,49 +1,258 @@ -# ESP8266 SLIP Network Interface Module -**Class Reference** +# ESP8266 WiFi Module Driver Documentation +## Overview + +This document explains how to use the ESP8266 WiFi module driver to enable the wireless connection function of IoT devices. This driver communicates with the ESP8266 module through the SLIP protocol and TLV data format, and supports the creation of WiFi access points (AP) and connection to mobile data networks. + +## Main Features +- WiFi Access Point Configuration: Supports custom SSID and password +- Automatic Routing Configuration: Enables seamless communication between networks +- Modular Management: Simple AP configuration and control of working modes +- Error Handling Mechanism: Comprehensive anomaly detection and handling + +## Quick Start +### 1. Import Required Modules + ```python -from esp8266 import Esp8266_ap +from machine import UART +from esp8266_ap import Esp8266_ap +import utime ``` -**Instantiation Parameters:** +### 2. Initialize the ESP8266 module +```python +# Initialize the ESP8266 module using the UART2 interface +esp = Esp8266_ap(UART.UART2) +``` +### 3. Set up a WiFi access point +```python +# Configure WiFi access point (SSID: MyAP, password: 12345678) +esp.set_ap(name='MyAP', pwd='12345678') +``` + + +### 4. Enable WiFi function + +```python +# Enable the WiFi module and complete the network configuration +if esp.wifi_on() == 0: + print('WiFi module has started successfully') + # Here, you can add the business logic after the device is connected to the network + while True: + utime.sleep(10) +else: +print('WiFi module startup failed') +``` + +## API Interface Description + +**`Esp8266_ap(uart)`** + + +Constructor, initializing the ESP8266 module. -| Name | Required | Type | Description | -|----|----|----|----| -|uart| Is| UART object| Used to connect to the UART interface of ESP8266| +**Parameter Description:** +- uart: UART interface instance -**Interface Function:** +**`set_ap(name=None, pwd=None, project_name='wifi_setap', project_version='1.0.0')`** -l **set_ap(name=None, pwd=None, project_name='wifi_setap', project_version='1.0.0')** -Configure the AP mode parameters of the ESP8266 module. +Configure the parameters of the WiFi access point. -**Parameters: ** +**Parameter Description:** -| Name | Required | Type | Description | -|----|----|----|----| -| name | No | str | WiFi network name | -| pwd | No | str | WiFi password | -| project_name | No | str | Network check project name, default 'wifi_setap' | -| project_version | No | str | Network check project version, default '1.0.0' | -Return value: +- name: WiFi access point name (SSID) +- pwd: WiFi access point password +- project_name: Project name (used for network detection) +- project_version: Project version (used for network detection) -0: Success +**Return Value:** --1: Failure +- 0: Success +- -1: Failure -l **wifi_on()** +**`wifi_on()`** -Enable the ESP8266 module and configure the SLIP network interface -Return value: +Enable the WiFi function and configure the network. + +**Return Value:** + +- 0: Success +- -1: Failure + +**`wifi_off()`** + + +Turn off the WiFi function to free up resources. + +## Application Example +Basic WiFi Access Point Configuration +```python +# Set custom SSID and password +esp.set_ap(name='Quectel_WiFi', pwd='SecurePass123') +``` +Open AP without password +```python +# Create an open access point without a password +esp.set_ap(name='Free_WiFi_Access') +``` +Password-protected AP +```python +# Create an access point that is password-protected but hides the SSID +esp.set_ap(pwd='HiddenNetworkPass') +``` +Multi-network collaboration applications +```python +esp = Esp8266_ap(UART.UART2) +esp.set_ap(name='IoT_Gateway', pwd='iot12345') + + +if esp.wifi_on() == 0: + print('The device has connected to both mobile network and WiFi network') + while True: + # Here, business logic for simultaneous access to dual networks can be added + # For example: Report data via mobile network, manage devices via local WiFi utime. + sleep(60) +``` +Network Health Monitoring +```python +import ujson -0: Success --1: Failure l **wifi_off()** +def network_health_check(): + # Check network status + esp_info = esp._wait_datacall_success() + return ujson.dumps(esp_info) -Turn off the ESP8266 module and release the resources +esp.set_ap(name='Network_Monitor') +esp.wifi_on() -Return value: None \ No newline at end of file +# Regularly report network status +while True: + status = network_health_check() + print("Current network status: {}".format(status)) + utime.sleep(300) +``` + +## Technical Description +### 1. Usage of the SLIP Protocol + +- Serial Line Interface Protocol (Serial Line IP) +- Operates based on UART communication +- Protocol type: SLIP_INNER (Internal Network) + +### 2. TLV Data Format +| Field | Length | Description | +|----|----|----| +| Head | 2 bytes | Identifier for data type (F1/F2/F3) | +| Length | 4 bytes | Length of data content (0000-9999) | +| Content | Variable length | Actual configuration data | + +**Headline:** + + +- F1: Password mode only +- F2: SSID mode only +- F3: Complete SSID + Password mode + +### 3. Routing Configuration + +- Default Gateway: 172.16.1.2 +- AP Address Range: 192.168.4.0/24 +- Subnet Mask: 255.255.255.0 + +## Network Configuration Parameters +### 1. Default Server + +- IP address: 172.16.1.5 + +- Port number: 100 + +### 2. Device Binding Address + +- IP address: 172.16.1.2 + +- Port number: 10001 + +### 3. Mobile Network Priority +| Network Type | Priority | +|----|----| +|LTE/5G| High | +|WiFi| Medium | +|Wired Network| Low | +## Network Configuration Parameters +### 1. Default Server + +- IP address: 172.16.1.5 +- Port number: 100 + +2. Device Binding Address + +- IP address: 172.16.1.2 +- Port number: 10001 + +### 3. Mobile Network Priority +| Network Type | Priority | +|----|----| +|LTE/5G| High | +|WiFi| Medium | +|Wired Network| Low | + +## Common Issues Troubleshooting +### 1. Initialization Failure + +- Phenomenon: "slip netif construct fail" error +- Solution: + - Check if the UART wiring is correct (TX/RX cross connection) + - Confirm that the UART baud rate settings are consistent (usually 115200) + - Verify if the power supply of the ESP8266 module is stable + +### 2. AP configuration failed + +- Phenomenon: Failure to set AP error +- Solution: + - Check the network connection status: checkNet.wait_network_connected() + - Confirm that the server address is reachable (172.16.1.5) + - Verify the length of the SSID and password (SSID: 1-32 characters, password: 8-64 characters) + +### 3. Network Routing Error + +- Phenomenon: Unable to access both networks simultaneously +- Solution: + - Confirm that the return value after calling wifi_on() is 0 + - Check if the routing table contains the 192.168.4.0/24 network segment + - Verify if the default gateway settings are correct + +### 4. Connection Stability Issues + +- Phenomenon: Frequent disconnections of connection +- Solution: + - Shorten the distance between the device and the AP + - Avoid interference from 2.4GHz frequency band (such as microwave ovens, Bluetooth devices) + - Update the ESP8266 firmware to the latest version + +**Connection status monitoring:** +```python +def check_connection(): + try: + # Attempt to access the server to verify the connection + sock = usocket.socket() + sock.connect(('172.16.1.5', 1000)) return True + except: + return False +``` +**Automatic Reconnection Mechanism:** +```python +while True: + if not check_connection(): + print("Connection lost. Attempting to reconnect..." ) + esp.wifi_off() + esp.set_ap(name='MyAP', pwd='password') + esp.wifi_on() + utime.sleep(60) +``` +This driver provides a complete WiFi configuration and management solution for the ESP8266 module. \ No newline at end of file diff --git a/libraries/ESP8266/README_zh.md b/libraries/ESP8266/README_zh.md new file mode 100644 index 0000000..78728c7 --- /dev/null +++ b/libraries/ESP8266/README_zh.md @@ -0,0 +1,230 @@ +# ESP8266 WiFi模块驱动文档 +## 概述 + +本文档介绍如何使用ESP8266 WiFi模块驱动实现物联网设备的无线连接功能。该驱动通过SLIP协议和TLV数据格式与ESP8266模块通信,支持创建WiFi接入点(AP)和连接移动数据网络。 + +## 主要特性 +- WiFi接入点配置:支持自定义SSID和密码 +- 自动路由配置:实现网络间无缝通信 +- 模块化管理:简洁的AP配置和工作模式控制 +- 错误处理机制:完善的异常检测和处理 + +## 快速入门 +### 1. 导入所需模块 + +```python +from machine import UART +from esp8266_ap import Esp8266_ap +import utime +``` + +### 2. 初始化ESP8266模块 +```python +# 使用UART2接口初始化ESP8266模块 +esp = Esp8266_ap(UART.UART2) +``` +### 3. 设置WiFi接入点 +```python +# 配置WiFi接入点(SSID:MyAP,密码:12345678) +esp.set_ap(name='MyAP', pwd='12345678') +``` + +### 4. 启用WiFi功能 + +```python +# 启用WiFi模块并完成网络配置 +if esp.wifi_on() == 0: + print('WiFi模块启动成功') + # 这里可以添加设备联网后的业务逻辑 + while True: + utime.sleep(10) +else: + print('WiFi模块启动失败') +``` +## API接口说明 + +**`Esp8266_ap(uart)`** + +构造函数,初始化ESP8266模块。 + +​​**参数说明:** + +- uart: UART接口实例 + +**`set_ap(name=None, pwd=None, project_name='wifi_setap', project_version='1.0.0')`** + + +配置WiFi接入点参数。 + +​**参数说明:​​** + +- name: WiFi接入点名称(SSID) +- pwd: WiFi接入点密码 +- project_name: 项目名称(用于网络检测) +- project_version: 项目版本(用于网络检测) + +​**​返回值:​​** + +- 0: 成功 +- -1: 失败 + +**`wifi_on()`** + +启用WiFi功能并配置网络。 + +​​**返回值:​​** + +- 0: 成功 +- -1: 失败 + +**`wifi_off()`** + +关闭WiFi功能,释放资源 + +## 应用示例 +基础WiFi接入点配置 +```python +# 设置自定义SSID和密码 +esp.set_ap(name='Quectel_WiFi', pwd='SecurePass123') +``` +无密码开放式AP +```python +# 创建无密码开放式接入点 +esp.set_ap(name='Free_WiFi_Access') +``` +仅密码保护的AP +```python +# 创建使用密码保护但隐藏SSID的接入点 +esp.set_ap(pwd='HiddenNetworkPass') +``` +多网络协作应用 +```python +esp = Esp8266_ap(UART.UART2) +esp.set_ap(name='IoT_Gateway', pwd='iot12345') + +if esp.wifi_on() == 0: + print('设备已连接到移动网络和WiFi网络') + + while True: + # 这里可以添加同时访问双网络的业务逻辑 + # 例如:通过移动网络上报数据,通过本地WiFi管理设备 + utime.sleep(60) +``` +网络健康监测 +```python +import ujson + +def network_health_check(): + # 检查网络状态 + esp_info = esp._wait_datacall_success() + return ujson.dumps(esp_info) + +esp.set_ap(name='Network_Monitor') +esp.wifi_on() + +# 定期上报网络状态 +while True: + status = network_health_check() + print("当前网络状态: {}".format(status)) + utime.sleep(300) +``` + +## 技术说明 +### 1. SLIP协议使用 + +- 串行线路接口协议(Serial Line IP) +- 工作在UART通信基础上 +- 协议类型: SLIP_INNER(内部网络) + +### 2. TLV数据格式 +|字段|长度|说明| +|----|----|----| +|头部|2字节|标识数据类型(F1/F2/F3)| +|长度|4字节|数据内容长度(0000-9999)| +|内容|变长|实际配置数据| + +​​**头部说明:​**​ + +- F1: 仅密码模式 +- F2: 仅SSID模式 +- F3: SSID+密码完整模式 + +### 3. 路由配置 + +- 默认网关: 172.16.1.2 +- AP地址段: 192.168.4.0/24 +- 子网掩码: 255.255.255.0 + +## 网络配置参数 +### 1. 默认服务器 + +- IP地址: 172.16.1.5 +- 端口号: 1000 + +### 2. 设备绑定地址 + +- IP地址: 172.16.1.2 +- 端口号: 10001 + +### 3. 移动网络优先级 +|网络类型|优先级| +|----|----| +|LTE/5G|高| +|WiFi| 中| +|有线网络|低| + +## 常见问题排查 +### 1. 初始化失败 + +- ​​现象​​: slip netif construct fail错误 +- ​​解决方案​​: + - 检查UART接线是否正确(TX/RX交叉连接) + - 确认UART波特率设置一致(通常115200) + - 验证ESP8266模块供电是否稳定 + +### 2. AP配置失败 + +- ​现象​​: fail to set ap错误 +- ​​解决方案​​: + - 检查网络连接状态checkNet.wait_network_connected() + - 确认服务器地址可达(172.16.1.5) + - 验证SSID和密码长度(SSID:1-32字符,密码:8-64字符) + +### 3. 网络路由异常 + +- ​​现象​​: 无法同时访问双网络 +- ​​解决方案​​: + - 确认调用wifi_on()后的返回值为0 + - 检查路由表是否包含192.168.4.0/24网段 + - 验证默认网关设置是否正确 + +### 4. 连接稳定性问题 + +- ​​现象​​: 连接频繁断开 +- ​​解决方案​​: + - 缩短设备与AP间的距离 + - 避免2.4GHz频段干扰(如微波炉、蓝牙设备) + - 更新ESP8266固件到最新版本 + +​​连接状态监控​​: +```python +def check_connection(): + try: + # 尝试访问服务器验证连接 + sock = usocket.socket() + sock.connect(('172.16.1.5', 1000)) + return True + except: + return False +``` +​​自动重连机制​​: +```python + while True: + if not check_connection(): + print('连接丢失,尝试重连...') + esp.wifi_off() + esp.set_ap(name='MyAP', pwd='password') + esp.wifi_on() + utime.sleep(60) +``` +本驱动为ESP8266模块提供了完整的WiFi配置和管理方案 diff --git a/libraries/HDC1080/README-zh.md b/libraries/HDC1080/README-zh.md deleted file mode 100644 index c65bb25..0000000 --- a/libraries/HDC1080/README-zh.md +++ /dev/null @@ -1,49 +0,0 @@ -# HDC1080 - -**类引用:** - -```python -from hdc1080 import Hdc1080 -``` - - - -**实例化参数:** - -| 名称 | 必填 | 类型 | 说明 | -| -------- | ---- | ---- | ----------------------- | -| i2c_obj | 是 | int | i2c对象 | -| dev_addr | 否 | int | i2c从设备地址,默认0x40 | - -```python -i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) -hdc = Hdc1080(i2c_dev) -``` - -**接口函数:** - -l **read()** - -​ 读取寄存器值转化成湿度和温度 - -参数: - -​ 无。 - -返回值: - -| 名称 | 类型 | 说明 | -| ---------------------- | ----- | ---------- | -| (humidity,temperature) | tuple | 湿度,温度 | - -l **reset()** - -​ 重置hdc1080 - -参数: - -​ 无。 - -返回值: - -​ 无。 diff --git a/libraries/HDC1080/README.md b/libraries/HDC1080/README.md index 43a182a..6e6ad04 100644 --- a/libraries/HDC1080/README.md +++ b/libraries/HDC1080/README.md @@ -1,56 +1,116 @@ -# HDC1080 +# HDC1080 Temperature and Humidity Sensor Driver Documentation +## Overview +This document explains how to use the HDC1080 temperature and humidity sensor driver module to measure the ambient temperature and humidity. This sensor provides high-precision temperature and humidity data via the I2C interface and is suitable for various environmental monitoring applications. +## Key Features -**Class Reference:** +- Measure both temperature and humidity simultaneously +- High-precision measurement (temperature ± 0.2°C, humidity ± 2%) +- Ultra-low power consumption design (typical 1.2 μA) +- I2C digital interface +- Fast response time +## Quick Start +### 1. Import Required Modules ```python +from machine import I2C from hdc1080 import Hdc1080 +import utime +``` +2. Initialize the sensors +```python +# Initialize the HDC1080 sensor on the I2C1 bus +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +sensor = Hdc1080(i2c_dev) +``` +3. Read temperature and humidity data +```python +# Read temperature and humidity data +humidity, temperature = sensor.read() +print("Temperature: {:.2f}°C, Humidity: {:.2f}%".format(temperature, humidity)) ``` +## API Interface Description +**`Hdc1080(i2c_obj, dev_addr=0x40)`** +Construct the constructor and initialize the HDC1080 sensor. +**Parameter Explanation:** -**Instantiation Parameters:** - -| Name | Required | Type | Description | -| -------- | ---- | ---- | ----------------------- | -| i2c_obj | Yes | int | I2C object | -| dev_addr | No | int | I2C slave device address, default 0x40 | -```python -i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) -hdc = Hdc1080(i2c_dev) -``` +- i2c_obj: I2C device instance +- dev_addr: Sensor I2C address (default 0x40) +**`read()`** -**Interface Function:** -l **read()** +Read and return the current temperature and humidity values. +**Return Value: ** -Read the register value and convert it into humidity and temperature +- (humidity, temperature): Humidity percentage value and temperature value +- humidity: Relative humidity (unit: %) +- temperature: Temperature (unit: °C) -Parameters: +**`reset()`** -No. -Return value: +Reset the sensor and restore factory settings. After the operation, the sensor needs to be reinitialized. -| Name | Type | Description | -| ---------------------- | ----- | ---------- | -| (humidity, temperature) | tuple | Humidity, Temperature | +## Application Examples -l **reset()** +Basic environmental monitoring +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +sensor = Hdc1080(i2c_dev) -Reset HDC1080 +while True: + humidity, temperature = sensor.read() + print("Temperature: {:.2f}°C, Humidity: {:.2f}%".format(temperature, humidity)) + utime.sleep(10) +``` -Parameters: -No. +Temperature anomaly alarm system +```python +def check_temperature_alert(temp, hum): + critical_alerts = [] + warnings = [] + + if temp > 35: + critical_alerts.append("High temperature alert!") + elif temp < 0: + critical_alerts.append("Low temperature alert!") + elif temp > 30: + warnings.append("High temperature") + elif temp < 5: + warnings.append("Low temperature") + if hum > 85: + warnings.append("Excessive humidity") + elif hum < 20: + warnings.append("Low humidity") + return critical_alerts, warnings + +sensor = Hdc1080(i2c_dev) +while True: + humidity, temperature = sensor.read() + critical, warnings = check_temperature_alert(temperature, humidity) + + if critical: + # Emergency Alert Processing Logic + print("⚠️ Emergency Alert:", ", ".join(critical)) + if warnings: + print("Warning:", ", ".join(warnings)) + utime.sleep(60) +``` -Return value: +## Common Issues Troubleshooting -No. \ No newline at end of file +- I2C address error (correct address 0x40) +- I2C bus not initialized +- Sensor power supply abnormal +- There is a heat source interference near the sensor +- Humidity sensor exposed to condensation environment \ No newline at end of file diff --git a/libraries/HDC1080/README_zh.md b/libraries/HDC1080/README_zh.md new file mode 100644 index 0000000..20de734 --- /dev/null +++ b/libraries/HDC1080/README_zh.md @@ -0,0 +1,115 @@ +# HDC1080温湿度传感器驱动文档 +## 概述 + +本文档介绍如何使用HDC1080温湿度传感器驱动模块测量环境温度和湿度。该传感器通过I2C接口提供高精度的温湿度数据,适用于各种环境监测应用。 +## 主要特性 + +- 同时测量温度和湿度 +- 高精度测量(温度±0.2°C,湿度±2%) +- 超低功耗设计(典型1.2μA) +- I2C数字接口 +- 快速响应时间 + +## 快速入门 +### 1. 导入所需模块 +```python +from machine import I2C +from hdc1080 import Hdc1080 +import utime +``` +### 2. 初始化传感器 +```python +# 在I2C1总线上初始化HDC1080传感器 +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +sensor = Hdc1080(i2c_dev) +``` +### 3. 读取温湿度数据 +```python +# 读取温湿度数据 +humidity, temperature = sensor.read() +print("温度: {:.2f}°C, 湿度: {:.2f}%".format(temperature, humidity)) +``` +## API接口说明 + +**`Hdc1080(i2c_obj, dev_addr=0x40)`** + +构造函数,初始化HDC1080传感器。 + +**​​参数说明:** + +- i2c_obj: I2C设备实例 +- dev_addr: 传感器I2C地址(默认0x40) + +**`read()`** + +读取并返回当前温度和湿度值。 + +​**​返回值:​​** + +- (humidity, temperature): 湿度百分比值和温度值 + - humidity: 相对湿度(单位:%) + - temperature: 温度(单位:°C) + +**`reset()`** + +重置传感器,恢复出厂设置。调用后需重新初始化传感器。 + +## 应用示例 + +基础环境监测 +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +sensor = Hdc1080(i2c_dev) + +while True: + humidity, temperature = sensor.read() + print("温度: {:.2f}°C, 湿度: {:.2f}%".format(temperature, humidity)) + utime.sleep(10) +``` + +温度异常警报系统 +```python +def check_temperature_alert(temp, hum): + critical_alerts = [] + warnings = [] + + if temp > 35: + critical_alerts.append("高温警报!") + elif temp < 0: + critical_alerts.append("低温警报!") + elif temp > 30: + warnings.append("温度偏高") + elif temp < 5: + warnings.append("温度偏低") + + if hum > 85: + warnings.append("湿度过高") + elif hum < 20: + warnings.append("湿度过低") + + return critical_alerts, warnings + +sensor = Hdc1080(i2c_dev) + +while True: + humidity, temperature = sensor.read() + critical, warnings = check_temperature_alert(temperature, humidity) + + if critical: + # 紧急警报处理逻辑 + print("⚠️ 紧急警报:", ", ".join(critical)) + # 这里可以添加短信、灯光报警等逻辑 + + if warnings: + print("警告:", ", ".join(warnings)) + + utime.sleep(60) +``` + +## 常见问题排查 + +- I2C地址错误(正确地址0x40) +- I2C总线未初始化 +- 传感器供电异常 +- 传感器附近有热源干扰 +- 湿度传感器暴露在冷凝环境中 \ No newline at end of file diff --git a/libraries/HDC2080/README-zh.md b/libraries/HDC2080/README-zh.md deleted file mode 100644 index 3549b78..0000000 --- a/libraries/HDC2080/README-zh.md +++ /dev/null @@ -1,53 +0,0 @@ -# HDC2080 - -**课程参考:** - -```python -from hdc2080 import Hdc2080 -`````` - - -**实例参数:** - -| 名称 | 必填项 | 类型 | 描述 | -| -------- | ---- | ---- | ----------------------- | -| i2c_obj | 是 | 整型 | I2C 对象 | -| dev_addr | 否 | 整型 | I2C 从设备地址,默认值为 0x40 | - -```python -i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) -hdc = Hdc2080(i2c_dev) -``` - - -**接口功能:** - -l **read()** - -读取寄存器中的值,并将其转换为湿度和温度。 - -参数: - - -否。 - - -返回值: - -| 名称 | 类型 | 描述 | -| ---------------------- | ----- | ---------- | -| (湿度,温度) | 元组 | 湿度、温度 | - -l **重置(函数)** - -重置 hdc1080 。 - -参数: - - -否。 - - -返回值: - -否。 \ No newline at end of file diff --git a/libraries/HDC2080/README.md b/libraries/HDC2080/README.md index eb5c216..006f399 100644 --- a/libraries/HDC2080/README.md +++ b/libraries/HDC2080/README.md @@ -1,49 +1,95 @@ -# HDC2080 +# HDC2080 Temperature and Humidity Sensor Driver Documentation +## Overview -**Class reference:** +This document explains how to use the HDC2080 temperature and humidity sensor driver module to accurately measure the ambient temperature and humidity. The sensor provides digital temperature and humidity data via the I2C interface, featuring low power consumption and high accuracy. +## Key Features +- High-precision temperature and humidity measurement (temperature ± 0.2°C, humidity ± 2%) +- Ultra-wide range: temperature (-40°C ~ 85°C), humidity (0% ~ 100%) +- Dual 16-bit analog-to-digital converters +- I2C digital interface (default address 0x40) +- Low power consumption mode (typical standby current 0.1μA) + +## Quick Start +### 1. Import Required Modules ```python +from machine import I2C from hdc2080 import Hdc2080 +import utime +``` +2. Initialize the sensors +```python +# Initialize the HDC2080 sensor on the I2C1 bus +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +sensor = Hdc2080(i2c_dev) +``` +3. Read temperature and humidity data +```python +# Read temperature and humidity data +humidity, temperature = sensor.read() +print("Temperature: {:.2f}°C, Humidity: {:.2f}%".format(temperature, humidity)) ``` +## API Interface Description +**`Hdc2080(i2c, addr=0x40)`** -**Instance parameters:** +Construct the constructor and initialize the HDC2080 sensor. -| Name | Required | Type | Description | -| -------- | ---- | ---- | ----------------------- | -| i2c_obj | Yes | int | I2C object | -| dev_addr | No | int | I2C slave device address, default 0x40 | +**Parameter Explanation:** -```python -i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) -hdc = Hdc2080(i2c_dev) -``` -**Interface function:** +- i2c: I2C device instance +- addr: Sensor I2C address (default 0x40) + +**`reset()`** + -l **read()** +Reset the sensor and restore to factory settings. -Read the register value and convert it into humidity and temperature. +**`read_temperature()`** -Parameters: -No. +Read the current temperature value. -Return value: +**Return Value:** -| Name | Type | Description | -| ---------------------- | ----- | ---------- | -| (humidity, temperature) | tuple | Humidity, Temperature | +Temperature value (unit: °C) -l **reset()** +**`read_humidity()`** -Reset hdc1080. -Parameters: +Read the current humidity value. -No. +**Return Value:** -Return value: +Humidity value (unit: %) + +**`read()`** + + +Trigger the temperature and humidity measurement and read the results. + +**`Return Value:`** + +- (humidity, temperature): Humidity percentage value and temperature value + +## Application Examples +Basic Environmental Monitoring +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +sensor = Hdc2080(i2c_dev) + + +while True: + humidity, temperature = sensor.read() + print("Temperature: {:.2f}°C, Humidity: {:.2f}%".format(temperature, humidity)) + utime.sleep(10) +``` -No. \ No newline at end of file +## Common Issues Troubleshooting +- I2C address error (correct address: 0x40) +- I2C bus not initialized +- Sensor power supply abnormal +- Interference from heat source near the sensor +- Humidity sensor exposed in a condensation environment \ No newline at end of file diff --git a/libraries/HDC2080/README_zh.md b/libraries/HDC2080/README_zh.md new file mode 100644 index 0000000..347a2ad --- /dev/null +++ b/libraries/HDC2080/README_zh.md @@ -0,0 +1,90 @@ +# HDC2080温湿度传感器驱动文档 +## 概述 + +本文档介绍如何使用HDC2080温湿度传感器驱动模块精确测量环境温度和湿度。该传感器通过I2C接口提供数字化的温湿度数据,具有低功耗和高精度的特点。 +## 主要特性 + +- 高精度温湿度测量(温度±0.2°C,湿度±2%) +- 超宽量程:温度(-40°C ~ 85°C),湿度(0% ~ 100%) +- 双16位模数转换器 +- I2C数字接口(默认地址0x40) +- 低功耗模式(典型0.1μA待机电流) + +## 快速入门 +### 1. 导入所需模块 +```python +from machine import I2C +from hdc2080 import Hdc2080 +import utime +``` +### 2. 初始化传感器 +```python +# 在I2C1总线上初始化HDC2080传感器 +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +sensor = Hdc2080(i2c_dev) +``` +### 3. 读取温湿度数据 +```python +# 读取温湿度数据 +humidity, temperature = sensor.read() +print("温度: {:.2f}°C, 湿度: {:.2f}%".format(temperature, humidity)) +``` + +## API接口说明 + +**`Hdc2080(i2c, addr=0x40)`** + +构造函数,初始化HDC2080传感器。 + +​​**参数说明:** + +- i2c: I2C设备实例 +- addr: 传感器I2C地址(默认0x40) + +**`reset()`** + +重置传感器,恢复出厂设置。 + +**`read_temperature()`** + +读取当前温度值。 + +​**​返回值:​​** + +- 温度值(单位:°C) + +**`read_humidity()`** + +读取当前湿度值。 + +​​**返回值:** + +- 湿度值(单位:%) + +**`read()`** + +触发温湿度测量并读取结果。 + +**`​​返回值:​​`** + +- (humidity, temperature): 湿度百分比值和温度值 + +## 应用示例 +基础环境监测 +```python +i2c_dev = I2C(I2C.I2C1, I2C.STANDARD_MODE) +sensor = Hdc2080(i2c_dev) + +while True: + humidity, temperature = sensor.read() + print("温度: {:.2f}°C, 湿度: {:.2f}%".format(temperature, humidity)) + utime.sleep(10) +``` + + +## 常见问题排查 +- I2C地址错误(正确地址0x40) +- I2C总线未初始化 +- 传感器供电异常 +- 传感器附近有热源干扰 +- 湿度传感器暴露在冷凝环境中 \ No newline at end of file diff --git a/libraries/L76K/README-zh.md b/libraries/L76K/README-zh.md deleted file mode 100644 index 439e767..0000000 --- a/libraries/L76K/README-zh.md +++ /dev/null @@ -1,130 +0,0 @@ -# GNSS 定位模块驱动 - -**类引用** -```python -from gnss_driver import Gnss -``` - -**实例化参数:** - -| 名称 | 必填 | 类型 | 说明 | -|----|----|----|----| -| uartn | 是 | int | UART端口号 | -|baudrate| 是| int| 波特率| -|databits| 是| int| 数据位| -|parity |是 |int |校验位| -|stopbits| 是| int| 停止位| -|flowctl| 是| int| 流控| - -**接口函数:** - -l read_gnss(retry=1, debug=0) - -读取GNSS原始数据。 - -​​**参数:**​​ - -| 名称 | 类型 | 默认值 | 说明 | -|----|----|----|----| -| retry | int | 1 | 重试次数 | -|debug| int| 0 |调试模式| - -​​返回值:​​ - --1:失败 - -(data_valid, data):成功 - -data_valid:数据有效位(0x01-0x07) - -data:原始GNSS数据 - -l isFix() - -检查是否定位成功 - -​​返回值:​​ - -1:定位成功 - -0:定位失败 - -l getUtcTime() - -获取定位的UTC时间 - -​​返回值:​​ - -成功:UTC时间字符串 - -失败:-1 - -l getLocationMode() - -获取定位模式 - -​​返回值:​​ - --1:获取失败 - -0:定位不可用 - -1:GPS/SPS模式 - -2:DGPS/DSPS模式 - -6:估算模式 - -l getUsedSateCnt() - -获取定位使用的卫星数量 - -​​返回值:​​ - - -成功:卫星数量 - -失败:-1 - -l getLocation() - -获取经纬度信息 - -​​返回值:​​ - -成功:(经度, 经度方向, 纬度, 纬度方向) - -失败:-1 - -getViewedSateCnt() - -获取可见卫星数量 - -​​返回值:​​ - - -成功:卫星数量 - -失败:-1 - -l getGeodeticHeight() - -获取海拔高度 - -​​返回值:​​ - -成功:海拔高度(米) -失败:-1 -getCourse() -获取卫星方位角 - -​​返回值:​​ - -字典:{卫星编号: 方位角} -getSpeed() -获取对地速度 - -​​返回值:​​ - -成功:速度(KM/h) -失败:-1 \ No newline at end of file diff --git a/libraries/L76K/README.md b/libraries/L76K/README.md index bfb1b3e..c5e877f 100644 --- a/libraries/L76K/README.md +++ b/libraries/L76K/README.md @@ -1,139 +1,228 @@ -# GNSS Positioning Module Driver +# GNSS Positioning Module Driver Documentation +## Overview + +This document explains how to use the GNSS positioning module driver to obtain satellite positioning data. This driver supports various functions for obtaining positioning data, including location, speed, altitude, key positioning information such as visible satellites. +## Main Features +- Obtain raw GNSS data (GGA/RMC/GSV format) +- Position status detection +- Obtain precise latitude and longitude coordinates +- Measure altitude and moving speed +- Statistics of visible satellites +- Positioning time acquisition +- Support for multiple positioning mode recognition + +## Quick Start +### 1. Import Required Modules +```python +from gnss import Gnss +import utime +``` +### 2. Initialize the GNSS module -"Class Reference" ```python -from gnss_driver import Gnss +# UART1 initializes the GNSS module (with a baud rate of 9600) +gnss = Gnss( + uartn = 1 # UART port number + baudrate = 9600 # Baud rate + databits = 8 # Data bits + parity = 0 # Parity + stopbits = 1 # Stop bits + flowctl = 0 # Flow control + ) ``` -**Instantiation Parameters:** +### 3. Obtain positioning data + +```python +# Obtain location information +if gnss.isFix(): + location = gnss.getLocation() + print("Latitude and Longitude: {}{}, {}{}".format(location[0], location[1], location[2], location[3])) +else: + print("Failed to locate successfully. Please wait..." ) +``` + +## API Interface Description -| Name | Required | Type | Description | -|----|----|----|----| -| uartn | is | int | UART port number | -| baudrate | is | int | Baud rate | -| databits | is | int | Data bits | -| parity | is | int | Parity | -| stopbits | is | int | Stop bits | -| flowctl | is | int | Flow control | +**`Gnss(uartn, baudrate, databits, parity, stopbits, flowctl)`** -**Interface Function:** -l read_gnss(retry=1, debug=0) +Construct the constructor and initialize the GNSS module. +**Parameter Explanation:** -Read the raw data of GNSS. -**Parameters:** +- uartn: UART port number (1, 2, etc.) +- baudrate: Communication baud rate (default 9600) +- databits: Data bits (usually 8) +- parity: Parity bit (0 - no parity check, 1 - odd parity check, 2 - even parity check) +- stopbits: Stop bits (1 or 2) +- flowctl: Flow control (0 - no flow control) -| Name | Type | Default Value | Description | -|----|----|----|----| -| retry | int | 1 | Number of retries | -| debug | int | 0 | Debug mode | +**`read_gnss(retry=1, debug=0)`** -Return value: --1: Failure +Read the original GNSS data. -(data_valid, data): Success +**Parameter Explanation:** -data_valid: Data Valid Bit (0x01 - 0x07) -data: Raw GNSS data +- retry: Number of retry attempts for reading +- debug: Switch for debug mode -l isFix() +**Return Value:** +- Success: (data_valid, data) +- Where data_valid is the valid bit identifier: +- 0x04: GGA is valid +- 0x02: RMC is valid +- 0x01: GSV is valid +- Failure: -1 -Check if the positioning was successful +**`isFix()`** -Return value: -1: Successful positioning +Check if the positioning was successful. -0: Positioning failed +**Return value:** -l getUtcTime() +- 1: Successfully located +- 0: Not yet located +**`getUtcTime()`** -Obtain the UTC time of the location -Return value: +Obtain the UTC time for positioning. -Success: UTC time string +**Return Value:** -Failure: -1 +- Success: UTC time string (formatted as "HHMMSS.SS") +- Failure: -1 -l getLocationMode() +**`getLocationMode()`** -Obtain positioning mode +Obtain the positioning mode. -Return value: +**Return Value:** --1: Failure in acquisition +- -1: Acquisition failed +- 0: Positioning is unavailable or invalid +- 1: GPS/SPS mode (standard positioning) +- 2: DGPS/DSPS mode (differential positioning) +- 6: Estimation mode (course position calculation) -0: Positioning is unavailable +**`getUsedSateCnt()`** -GPS/SPS mode -2: DGPS/DSPS Mode +Obtain the number of satellites used for positioning. -6: Estimation Mode +**Return Value:** -l getUsedSateCnt() +- Success: Number of satellites used +- Failure: -1 +**`getLocation()`** -Obtain the number of satellites used for positioning -Return value: +Obtain precise latitude and longitude information. +**Return Value:** +- Success: (longitude, lon_direction, latitude, lat_direction) + - longitude: Longitude value (floating point number) + - lon_direction: Longitude direction ('E' or 'W') + - latitude: Latitude value (floating point number) + - lat_direction: Latitude direction ('N' or 'S') +- Failure: -1 -Success: Number of Satellites +**`getViewedSateCnt()`** -Failure: -1 -l getLocation() +Obtain the number of visible satellites. +**Return Value:** -Obtain latitude and longitude information +- Success: Visible satellite count +- Failure: -1 -Return value: +**`getGeodeticHeight()`** -Success: (Longitude, Longitude direction, Latitude, Latitude direction) -Failure: -1 +Obtain the altitude. -getViewedSateCnt() +**Return Value:** +- Success: Altitude (unit: meters) +- Failure: -1 -Obtain the number of visible satellites +**`getCourse()`** -Return value: +Obtain the azimuth angle of the visible satellite. +**Return Value:** -Success: Number of Satellites +- Success: Satellite azimuth data in dictionary format, key is satellite number, value is azimuth +- Failure: -1 -Failure: -1 +**`getSpeed()`** -l getGeodeticHeight() +Obtain the ground speed. -Obtain the altitude +**Return Value:** -Return value: +- Success: Ground speed (unit: km/h) +- Failure: -1 -Success: Altitude (meters) -Failure: -1 getCourse() -Obtain the satellite azimuth angle +## Application Examples +Basic Positioning Application +```python +gnss = Gnss(1, 9600, 8, 0, 1, 0) + +while True: + if gnss.isFix(): + # Obtain location information + lon, lon_dir, lat, lat_dir = gnss.getLocation() + height = gnss.getGeodeticHeight() + speed = gnss.getSpeed() + + print("Location: {:.6f}{}, {:.6f}{}".format(lat, lat_dir, lon, lon_dir)) + print("Altitude: {} meters, Speed: {} km/h".format(height, speed)) + else: + used_sats = gnss.getUsedSateCnt() + visible_sats = gnss.getViewedSateCnt() + print("Locating... Using satellites: {}, Visible satellites: {}".format(used_sats, visible_sats)) + utime.sleep(1) +``` -Return value: -Dictionary: {Satellite Number: Azimuth} getSpeed() -Obtain the ground speed -Return value: +Satellite information analysis +```python +gnss = Gnss(1, 9600, 8, 0, 1, 0) + +def analyze_satellites(): +while not gnss.isFix(): + utime.sleep(1) + + # Obtain satellite azimuth information + satellite_data = gnss.getCourse() + visible_sats = gnss.getViewedSateCnt() + + print("A total of {} satellites can be seen:".format(visible_sats)) + for sat_id, azimuth in satellite_data.items(): + print("Satellite {}: Azimuth {}°".format(sat_id, azimuth)) + +analyze_satellites() +``` + +## Common Issues Troubleshooting +### Long-term Failure to Locate -Success: Speed (KM/h) -Failure: -1 \ No newline at end of file +- Possible causes: +- Poor or damaged antenna connection +- Positioning module not powered on +- Poor satellite signal in the current environment \ No newline at end of file diff --git a/libraries/L76K/README_zh.md b/libraries/L76K/README_zh.md new file mode 100644 index 0000000..8280489 --- /dev/null +++ b/libraries/L76K/README_zh.md @@ -0,0 +1,218 @@ +# GNSS定位模块驱动文档 +## 概述 + +本文档介绍如何使用GNSS定位模块驱动获取卫星定位数据。该驱动支持多种定位数据获取功能,包括位置、速度、海拔、可见卫星等关键定位信息。 +## 主要特性 +- 获取原始GNSS数据(GGA/RMC/GSV格式) +- 定位状态检测 +- 获取精确的经纬度坐标 +- 测量海拔高度和移动速度 +- 可见卫星信息统计 +- 定位时间获取 +- 支持多种定位模式识别 + +## 快速入门 +### 1. 导入所需模块 +```python +from gnss import Gnss +import utime +``` +### 2. 初始化GNSS模块 + +```python +# UART1初始化GNSS模块(波特率9600) +gnss = Gnss( + uartn=1, # UART端口号 + baudrate=9600, # 波特率 + databits=8, # 数据位 + parity=0, # 校验位 + stopbits=1, # 停止位 + flowctl=0 # 流控 +) +``` + +### 3. 获取定位数据 + +```python +# 获取定位信息 +if gnss.isFix(): + location = gnss.getLocation() + print("经纬度: {}{}, {}{}".format(location[0], location[1], location[2], location[3])) +else: + print("尚未定位成功,请等待...") +``` + +## API接口说明 + +**`Gnss(uartn, baudrate, databits, parity, stopbits, flowctl)`** + +构造函数,初始化GNSS模块。 + +**​​参数说明:​​** + +- uartn: UART端口号 (1, 2等) +- baudrate: 通信波特率 (默认9600) +- databits: 数据位 (通常为8) +- parity: 校验位 (0-无校验, 1-奇校验, 2-偶校验) +- stopbits: 停止位 (1或2) +- flowctl: 流控 (0-无流控) + +**`read_gnss(retry=1, debug=0)`** + +读取原始GNSS数据。 + +​​**参数说明:​​** + +- retry: 读取重试次数 +- debug: 调试模式开关 + +​**​返回值:​​** + +- 成功: (data_valid, data) +- 其中data_valid为有效位标识: + - 0x04: GGA有效 + - 0x02: RMC有效 + - 0x01: GSV有效 +- 失败: -1 + +**`isFix()`** + +检查是否定位成功。 + +​**​返回值:​​** + +- 1: 定位成功 +- 0: 尚未定位 + +**`getUtcTime()`** + +获取定位的UTC时间。 + +​**​返回值:​​** + +- 成功: UTC时间字符串 (格式为"HHMMSS.SS") +- 失败: -1 + +**`getLocationMode()`** + +获取定位模式。 + +​​**返回值:​​** + +- -1: 获取失败 +- 0: 定位不可用或无效 +- 1: GPS/SPS模式 (标准定位) +- 2: DGPS/DSPS模式 (差分定位) +- 6: 估算模式 (航位推算) + +**`getUsedSateCnt()`** + +获取定位使用的卫星数量。 + +​**​返回值:​​** + +- 成功: 使用卫星数量 +- 失败: -1 + +**`getLocation()`** + +获取精确的经纬度信息。 + +​**​返回值:​​** + +- 成功: (longitude, lon_direction, latitude, lat_direction) + - longitude: 经度值 (浮点数) + - lon_direction: 经度方向 ('E'或'W') + - latitude: 纬度值 (浮点数) + - lat_direction: 纬度方向 ('N'或'S') +- 失败: -1 + +**`getViewedSateCnt()`** + +获取可见卫星数量。 + +​​**返回值:** + +- 成功: 可见卫星数量 +- 失败: -1 + +**`getGeodeticHeight()`** + +获取海拔高度。 + +​​**返回值:** + +- 成功: 海拔高度 (单位: 米) +- 失败: -1 + +**`getCourse()`** + +获取可见卫星的方位角。 + +​​**返回值:**​ + +- 成功: 字典格式的卫星方位角数据,key为卫星编号,value为方位角 +- 失败: -1 + +**`getSpeed()`** + +获取对地速度。 + +​**​返回值:​​** + +- 成功: 对地速度 (单位: km/h) +- 失败: -1 + +## 应用示例 +基本定位应用 +```python +gnss = Gnss(1, 9600, 8, 0, 1, 0) + +while True: + if gnss.isFix(): + # 获取位置信息 + lon, lon_dir, lat, lat_dir = gnss.getLocation() + height = gnss.getGeodeticHeight() + speed = gnss.getSpeed() + + print("位置: {:.6f}{}, {:.6f}{}".format(lat, lat_dir, lon, lon_dir)) + print("海拔: {}米, 速度: {}km/h".format(height, speed)) + else: + used_sats = gnss.getUsedSateCnt() + visible_sats = gnss.getViewedSateCnt() + print("定位中... 使用卫星: {}, 可见卫星: {}".format(used_sats, visible_sats)) + + utime.sleep(1) +``` + + +卫星信息分析 +```python +gnss = Gnss(1, 9600, 8, 0, 1, 0) + +def analyze_satellites(): + while not gnss.isFix(): + utime.sleep(1) + + # 获取卫星方位角信息 + satellite_data = gnss.getCourse() + visible_sats = gnss.getViewedSateCnt() + + print("共可见 {} 颗卫星:".format(visible_sats)) + for sat_id, azimuth in satellite_data.items(): + print("卫星 {}: 方位角 {}°".format(sat_id, azimuth)) + +analyze_satellites() +``` + + +## 常见问题排查 +### 长时间无法定位 + +- ​可能原因:​​ + - 天线接触不良或损坏 + - 定位模块未上电 + - 当前环境卫星信号差 + + + diff --git a/libraries/LCD/README-zh.md b/libraries/LCD/README-zh.md deleted file mode 100644 index 5111b82..0000000 --- a/libraries/LCD/README-zh.md +++ /dev/null @@ -1,319 +0,0 @@ -# LCD 应用指导文档 - -## 接口说明 - -### st7789 - -**类引用:** - -```python -from peripheral.lcd.st7789 import St7789 -``` - - - -**实例化参数:** - -| 名称 | 必填 | 类型 | 说明 | -| -------- | ---- | ----- | ----------------------- | -| InitData | 否 | tuple | 传入 LCD 的配置命令 | -| width | 否 | int | LCD 屏幕的宽度,默认240 | -| height | 否 | int | LCD 屏幕的高度,默认240 | -| clk | 否 | int | LCD SPI 时钟,默认13000 | - -``` -lcd_test = St7789() -``` - -**接口函数:** - -l **DrawPoint(x, y, color)** - -​ 画点。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| x | 是 | int | x坐标 | -| y | 是 | int | y坐标 | -| color | 是 | int | 颜色
红色:0xF800
绿色: 0x07E0
蓝色: 0x001F
白色: 0xFFFF
黑色: 0x0000
| - -返回值: - -​ 无 - -l **Clear (color)** - -​ 清屏。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| color | 是 | int | 颜色
红色:0xF800
绿色: 0x07E0
蓝色: 0x001F
白色: 0xFFFF
黑色: 0x0000
| - -返回值: - -​ 无 - -l **Fill(x_s, y_s, x_e, y_e, color)** - -​ 填充以起始坐标和结束坐标为对角线的矩形。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| x_s | 是 | int | 起始x坐标 | -| y_s | 是 | int | 起始y坐标 | -| x_e | 是 | int | 结束x坐标 | -| y_e | 是 | int | 结束x坐标 | -| color | 是 | int | 颜色
红色:0xF800
绿色: 0x07E0
蓝色: 0x001F
白色: 0xFFFF
黑色: 0x0000
| - -返回值: - -​ 无 - -l **DrawLine(x0, y0, x1, y1, color)** - -​ 画线。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| x0 | 是 | int | 起始x坐标 | -| y0 | 是 | int | 起始y坐标 | -| x1 | 是 | int | 结束x坐标 | -| y1 | 是 | int | 结束x坐标 | -| color | 是 | int | 颜色
红色:0xF800
绿色: 0x07E0
蓝色: 0x001F
白色: 0xFFFF
黑色: 0x0000
| - -返回值: - -​ 无 - -l **DrawRectangle (x0, y0, x1, y1, color)** - -​ 画矩形。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| x0 | 是 | int | 起始x坐标 | -| y0 | 是 | int | 起始y坐标 | -| x1 | 是 | int | 结束x坐标 | -| y1 | 是 | int | 结束x坐标 | -| color | 是 | int | 颜色
红色:0xF800
绿色: 0x07E0
蓝色: 0x001F
白色: 0xFFFF
黑色: 0x0000
| - -返回值: - -​ 无 - -l **DrawCircle (x0, y0, r, color)** - -​ 画矩形。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| x0 | 是 | int | 起始x坐标 | -| y0 | 是 | int | 起始y坐标 | -| r | 是 | int | 半径 | -| color | 是 | int | 颜色
红色:0xF800
绿色: 0x07E0
蓝色: 0x001F
白色: 0xFFFF
黑色: 0x0000
| - -返回值: - -​ 无 - -l **DrawCircle (x0, y0, r, color)** - -​ 画矩形。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| x0 | 是 | int | 起始x坐标 | -| y0 | 是 | int | 起始y坐标 | -| r | 是 | int | 半径 | -| color | 是 | int | 颜色
红色:0xF800
绿色: 0x07E0
蓝色: 0x001F
白色: 0xFFFF
黑色: 0x0000
| - -返回值: - -​ 无 - -l **ShowChar(x, y, xsize, ysize, ch_buf, fc, bc)** - -​ 单字符串显示。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ------ | ---- | ---- | ---------------------- | -| x | 是 | int | x坐标 | -| y | 是 | int | y坐标 | -| xsize | 是 | int | 字体宽度 | -| ysize | 是 | int | 字体高度 | -| ch_buf | 是 | int | 存放字符的元组或者列表 | -| fc | 是 | int | 字体颜色,RGB565 | -| bc | 是 | int | 背景颜色,RGB565 | - -返回值: - -​ 无 - -l **ShowAscii (x, y, xsize, ysize, ch_buf, fc, bc)** - -​ ASCII字符显示。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ------ | ---- | ---- | --------------------------- | -| x | 是 | int | x坐标 | -| y | 是 | int | y坐标 | -| xsize | 是 | int | 字体宽度 | -| ysize | 是 | int | 字体高度 | -| ch_buf | 是 | int | 存放ascii字符的元组或者列表 | -| fc | 是 | int | 字体颜色,RGB565 | -| bc | 是 | int | 背景颜色,RGB565 | - -返回值: - -​ 无 - -l **ShowAsciiStr(x, y, xsize, ysize, str_ascii, fc, bc)** - -​ ASCII字符串显示。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| --------- | ---- | ---- | ------------------- | -| x | 是 | int | x坐标 | -| y | 是 | int | y坐标 | -| xsize | 是 | int | 字体宽度 | -| ysize | 是 | int | 字体高度 | -| str_ascii | 是 | int | 待显示的ASCII字符串 | -| fc | 是 | int | 字体颜色,RGB565 | -| bc | 是 | int | 背景颜色,RGB565 | - -返回值: - -​ 无 - -l **ShowJpg(name, start_x, start_y)** - -​ 显示图片,若大于屏幕则缩小显示在屏幕中间。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ------- | ---- | ---- | --------- | -| name | 是 | str | 图片路径 | -| start_x | 是 | int | 起始x坐标 | -| start_y | 是 | int | 起始y坐标 | - -返回值: - -​ 无 - -l **lcd_show_image(image_data, x, y, width, heigth)** - -​ bytearray图片显示,如果图片宽高小于80x80,可直接该函数一次性写入并显示。 - -参数: - -| 名称 | 必填 | 类型 | 说明 | -| ---------- | ---- | --------- | --------- | -| image_data | 是 | bytearray | 图片路径 | -| x | 是 | int | 起始x坐标 | -| y | 是 | int | 起始y坐标 | -| width | 是 | int | 图片宽度 | -| height | 是 | int | 图片高度 | - -返回值: - -​ 无 - - - -### st7735 - -**类引用:** - -```python -from peripheral.lcd.st7735 import St7735 -``` - - - -**实例化参数:** - -| 名称 | 必填 | 类型 | 说明 | -| -------- | ---- | ----- | ----------------------- | -| InitData | 否 | tuple | 传入 LCD 的配置命令 | -| width | 否 | int | LCD 屏幕的宽度,默认128 | -| height | 否 | int | LCD 屏幕的高度,默认160 | -| clk | 否 | int | LCD SPI 时钟,默认13000 | - -```python -lcd_test = St7735() -``` - -**接口函数:** - -同st7789 - - - -### ili9225 - -**类引用:** - -```python -from peripheral.lcd.ili9225 import Ili9225 -``` - - - -**实例化参数:** - -| 名称 | 必填 | 类型 | 说明 | -| -------- | ---- | ----- | ----------------------- | -| InitData | 否 | tuple | 传入 LCD 的配置命令 | -| width | 否 | int | LCD 屏幕的宽度,默认176 | -| height | 否 | int | LCD 屏幕的高度,默认220 | -| clk | 否 | int | LCD SPI 时钟,默认13000 | - -**接口函数:** - -同st7789 - - - -### ili9341 - -**类引用:** - -```python -from peripheral.lcd.ili9341 import Ili9341 -``` - - - -**实例化参数:** - -| 名称 | 必填 | 类型 | 说明 | -| -------- | ---- | ----- | ----------------------- | -| InitData | 否 | tuple | 传入 LCD 的配置命令 | -| width | 否 | int | LCD 屏幕的宽度,默认320 | -| height | 否 | int | LCD 屏幕的高度,默认240 | -| clk | 否 | int | LCD SPI 时钟,默认13000 | - -**接口函数:** - -同st7789 diff --git a/libraries/LCD/README.md b/libraries/LCD/README.md index 6ad648d..15c0513 100644 --- a/libraries/LCD/README.md +++ b/libraries/LCD/README.md @@ -1,181 +1,315 @@ -# LCD Application Guide Document - -## Interface Description - -### st7789 +# LCD Universal Driver Documentation +## Overview + +This document explains how to use the LCD universal driver module to achieve various display functions. This driver provides a rich set of drawing and display interfaces, supporting basic graphic drawing such as points, lines, rectangles, and circles, as well as the display of characters, Chinese characters, images, etc. +## Main Features +- Supports basic graphic drawing: points, lines, rectangles, circles +- Supports ASCII character display (8x16, 16x24) +- Supports Chinese character display (16x16, 16x24, 24x24) +- Supports image display (JPG format or RGB data) +- Supports clearing the screen and area filling +- Supports RGB565 color format +- Provides color conversion tool functions + +## Quick Start +### 1. Create an LCD subclass +```python +from machine import LCD +from usr import Peripheral_LCD + + +class MyLCD(Peripheral_LCD): + def __init__(self): + # Initialize the actual LCD device + self._lcd = LCD() + self._lcd.lcd_init() + self._lcd_w = 240 # LCD width + self._lcd_h = 320 # LCD height + # Call the initialization of the parent + class super().__init__(self) +# Create an LCD instance +lcd = MyLCD() +``` +### 2. Basic Drawing Operations +```python +# Clear screen to white +lcd.Clear(0xFFFF) +# Draw a red rectangle +lcd.DrawRectangle(50, 50, 150, 150, 0xF800) -**Class Reference:** +# Draw a blue circle +lcd.DrawCircle(120, 160, 50, 0x001F) +# Draw the green diagonal line +lcd.DrawLine(0, 0, 239, 319, 0x07E0) +``` +### 3. Text Display ```python -from peripheral.lcd.st7789 import St7789 +# Display ASCII string +lcd.ShowAsciiStr(10, 10, 8, 16, "Hello World!" , 0x0000, 0xFFFF) + +# Display Chinese characters +lcd.lcd_show_chinese_str(10, 30, 16, 16, "Chinese Test", 0x0000, 0xFFFF) ``` +## API Interface Description +**`DrawPoint(x, y, color)`** +Draw a point at the designated position. +**Parameter Explanation:** -**Instantiation Parameters:** -| Name | Required | Type | Description | -| -------- | ---- | ----- | ----------------------- | -| InitData | No | tuple | Configuration commands to be sent to the LCD | -| width | No | int | Width of the LCD screen, default 240 | -| height | No | int | Height of the LCD screen, default 240 | -| clk | No | int | LCD SPI clock, default 13000 | +- x: X coordinate +- y: Y coordinate +- color: RGB565 color value -``` -lcd_test = St7789() -``` +**`Clear(color)`** + + +Clear the screen using the specified color. + +**Parameter Explanation:** + +- color: RGB565 color value + +**`Fill(x_s, y_s, x_e, y_e, color)`** + + +Fill the specified rectangular area. + +**Parameter Explanation:** + + +- x_s: Initial X coordinate +- y_s: Initial Y coordinate +- x_e: End X coordinate +- y_e: End Y coordinate +- color: RGB565 color value + +**`DrawLine(x0, y0, x1, y1, color)`** + + +Draw a straight line. + +**Parameter Explanation:** -**Interface Function: ** +- x0, y0: Starting coordinates +- x1, y1: Ending coordinates +- color: RGB565 color value -l **DrawPoint(x, y, color)** +**`DrawRectangle(x0, y0, x1, y1, color)`** +Draw a rectangular border. -Make a dot. +**Parameter Explanation:** -Parameters: -| Name | Required | Type | Description | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| x | Yes | int | X coordinate | -| y | Yes | int | Y coordinate | -| color | Yes | int | Color
Red: 0xF800
Green: 0x07E0
Blue: 0x001F
White: 0xFFFF
Black: 0x0000 | +- x0, y0: Top-left coordinate +- x1, y1: Bottom-right coordinate +- color: RGB565 color value -Return value: +**`DrawCircle(x0, y0, r, color)`** -No +Draw a circle. -l **Clear (color)** +**Parameter Explanation:** -Clear the screen. +- x0, y0: Coordinates of the center of the circle +- r: Radius +- color: RGB565 color value -Parameters: +**`ShowChar(x, y, xsize, ysize, ch_buf, fc, bc)`** -| Name | Required | Type | Description | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| Color | Yes | int | Color
Red: 0xF800
Green: 0x07E0
Blue: 0x001F
White: 0xFFFF
Black: 0x0000 | -Return value: +Display individual characters (supporting Chinese characters and ASCII). -No +**Parameter Explanation:** -l **Fill(x_s, y_s, x_e, y_e, color)** +- x, y: Display position +- xsize, ysize: Character size +- ch_buf: Character bitmap data +- fc: Foreground color (RGB565) +- bc: Background color (RGB565) +**`ShowAscii(x, y, xsize, ysize, ch, fc, bc)`** -Fill a rectangle whose diagonal is defined by the starting and ending coordinates. -Parameters: +Display ASCII characters. -| Name | Required | Type | Description | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| x_s | Yes | int | Starting x-coordinate | -| y_s | Yes | int | Starting y-coordinate | -| x_e | Yes | int | Ending x-coordinate | -| y_e | Yes | int | Ending y-coordinate | -| color | Yes | int | Color
Red: 0xF800
Green: 0x07E0
Blue: 0x001F
White: 0xFFFF
Black: 0x0000
| +**Parameter Explanation:** -Return value: -No +- x, y: Display position +- xsize, ysize: Character size +- ch: ASCII character +- fc: Foreground color (RGB565) +- bc: Background color (RGB565) +**`ShowAsciiStr(x, y, xsize, ysize, str_ascii, fc, bc)`** -l **DrawLine(x0, y0, x1, y1, color)** +Display the ASCII string. -Underline. +**Parameter Explanation:** -Parameters: -| Name | Required | Type | Description | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| x0 | Yes | int | Starting x-coordinate | -| y0 | Yes | int | Starting y-coordinate | -| x1 | Yes | int | Ending x-coordinate | -| y1 | Yes | int | Ending y-coordinate | -| color | Yes | int | Color
Red: 0xF800
Green: 0x07E0
Blue: 0x001F
White: 0xFFFF
Black: 0x0000
| +- x, y: Starting position +- xsize, ysize: Character size +- str_ascii: ASCII string +- fc: Foreground color (RGB565) +- bc: Background color (RGB565) -Return value: +**`ShowJpg(name, start_x, start_y)`** -No +Display JPG image. -l **DrawRectangle (x0, y0, x1, y1, color)** +**Parameter Explanation:** -Draw a rectangle. +- name: File name of the image +- start_x, start_y: Display position -Parameters: +**`lcd_show_chinese(x, y, xsize, ysize, ch, fc, bc)`** -| Name | Required | Type | Description | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| x0 | Yes | int | Starting x-coordinate | -| y0 | Yes | int | Starting y-coordinate | -| x1 | Yes | int | Ending x-coordinate | -| y1 | Yes | int | Ending y-coordinate | -| color | Yes | int | Color
Red: 0xF800
Green: 0x07E0
Blue: 0x001F
White: 0xFFFF
Black: 0x0000
| +Display a single Chinese character. -Return value: +**Parameter Explanation:** -No +- x, y: Display position +- xsize, ysize: Character size +- ch: Chinese character +- fc: Foreground color (RGB565) +- bc: Background color (RGB565) -l **DrawCircle (x0, y0, r, color)** +**`lcd_show_chinese_str(x, y, xsize, ysize, str_ch, fc, bc)`** -Draw a rectangle. +Display the Chinese character string. -Parameters: +**Parameter Explanation:** -| Name | Required | Type | Description | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| x0 | Yes | int | Initial x-coordinate | -| y0 | Yes | int | Initial y-coordinate | -| r | Yes | int | Radius | -| color | Yes | int | Color
Red: 0xF800
Green: 0x07E0
Blue: 0x001F
White: 0xFFFF
Black: 0x0000
| -Return value: +- x, y: Starting position +- xsize, ysize: Character size +- str_ch: Chinese character string +- fc: Foreground color (RGB565) +- bc: Background color (RGB565) -No +**`lcd_show_image(image_data, x, y, width, height)`** -l **DrawCircle (x0, y0, r, color)** +Display the RGB data image. +**Parameter Explanation:** -Draw a rectangle. -Parameters: +- image_data: RGB565 格式的图片数据 +- x, y: Display position +- width, height: Image size -| Name | Required | Type | Description | -| ----- | ---- | ---- | ------------------------------------------------------------ | -| x0 | Yes | int | Initial x-coordinate | -| y0 | Yes | int | Initial y-coordinate | -| r | Yes | int | Radius | -| color | Yes | int | Color
Red: 0xF800
Green: 0x07E0
Blue: 0x001F
White: 0xFFFF
Black: 0x0000 | +**`lcd_show_image_file(path, x, y, width, height, h)`** -Return value: -No +Display image files (supporting segmented display of large images). +**Parameter Explanation:** -l **ShowChar(x, y, xsize, ysize, ch_buf, fc, bc)** +- path: Path of the image file +- x, y: Display position +- width, height: Image size +- h: Segmentation height (it is recommended that widthh2 < 4096) -Single string display. +**`get_rgb565_color(r, g, b)`** + + +RGB888 to RGB565 color conversion. + +**Parameter Explanation:** + + +- r: Red component (0 - 255) +- g: Green component (0 - 255) +- b: Blue component (0 - 255) + +**Return Value:** + +RGB565 color value + +## Application Example + +Create a digital clock interface +```python +def digital_clock(lcd): + # Clear screen to a dark blue color + lcd.Clear(0x0019) + + # Draw the outer frame of the clock + lcd.DrawRectangle(50, 50, 190, 110, 0xFFFF) + lcd.Fill(51, 51, 189, 109, 0x0000) + + # Display time label + lcd.ShowAsciiStr(60, 60, 8, 16, "TIME:", 0xFFFF, 0x0000) + +# Updated Time Display +while True: + # Obtain the current time + current_time = "12:34:56" + + # Clear Old Time + lcd.Fill(100, 60, 180, 75, 0x0000) + + # Display new time + lcd.ShowAsciiStr(100, 60, 16, 24, current_time, 0xFFFF, 0x0000) + + utime.sleep(1) + +# Usage Example +lcd = MyLCD() +digital_clock(lcd) +``` + + +Display the sensor data dashboard +```python +def sensor_dashboard(lcd, temp, humi, press): + # Clear Screen + lcd.Clear(0xFFFF) + + # Display Title + lcd.lcd_show_chinese_str(80, 10, 24, 24, "Environmental Monitoring", 0x0000, 0xFFFF) + # Temperature Display + lcd.lcd_show_chinese_str(30, 50, 16, 16, "Temperature:", 0x0000, 0xFFFF) lcd.ShowAsciiStr(80, 50, 16, 24, "{:.1f}°C".format(temp), 0xF800, 0xFFFF) + + # Humidity Display + lcd.lcd_show_chinese_str(30, 90, 16, 16, "Humidity:", 0x0000, 0xFFFF) lcd.ShowAsciiStr(80, 90, 16, 24, "{:.1f}%".format(humi), 0x001F, 0xFFFF) + + # Pressure Display + lcd.lcd_show_chinese_str(30, 130, 16, 16, "Pressure:", 0x0000, 0xFFFF) lcd.ShowAsciiStr(80, 130, 16, 24, "{:.1f}hPa".format(press), 0x07E0, 0xFFFF) + + # Draw a divider line + lcd.DrawLine(20, 170, 220, 170, 0x0000) + + # Status Indication + status = "Normal" if 18 <= temp <= 28 and 40 <= humi <= 60 else "Exception" + color = 0x07E0 if status == "Normal" else 0xF800 + lcd.lcd_show_chinese_str(80, 190, 16, 16, "Status: {}".format(status), color, 0xFFFF) + + # Usage Example + sensor_dashboard(lcd, 25.5, 45.2, 1013.2) +``` -Parameters: -| Name | Required | Type | Description | -| ------ | ---- | ---- | ---------------------- | -| x | Yes | int | X coordinate | -| y | Yes | int | Y coordinate | -| xsize | Yes | int | Font width | -| ysize | Yes | int | Font height | -| ch_buf | Yes | int | Tuple or list storing characters | -| fc | Yes | int | Font color, RGB565 | -| bc | Yes | int | Background color, RGB5 \ No newline at end of file +## Common Issues Troubleshooting +- Verify if the coordinates are beyond the screen boundaries +- Ensure that the image data is in the RGB565 format +- Use a conversion tool to preprocess the image \ No newline at end of file diff --git a/libraries/LCD/README_zh.md b/libraries/LCD/README_zh.md new file mode 100644 index 0000000..c680f90 --- /dev/null +++ b/libraries/LCD/README_zh.md @@ -0,0 +1,292 @@ +# LCD通用驱动文档 +## 概述 + +本文档介绍如何使用LCD通用驱动模块实现各种显示功能。该驱动提供了丰富的绘图和显示接口,支持点、线、矩形、圆形等基本图形绘制,以及字符、汉字、图片等内容的显示。 +## 主要特性 +- 支持基本图形绘制:点、线、矩形、圆形 +- 支持ASCII字符显示(8x16、16x24) +- 支持汉字显示(16x16、16x24、24x24) +- 支持图片显示(JPG格式或RGB数据) +- 支持清屏和区域填充 +- 支持RGB565颜色格式 +- 提供颜色转换工具函数 + +## 快速入门 +### 1. 创建LCD子类 +```python +from machine import LCD +from usr import Peripheral_LCD + +class MyLCD(Peripheral_LCD): + def __init__(self): + # 初始化实际LCD设备 + self._lcd = LCD() + self._lcd.lcd_init() + self._lcd_w = 240 # LCD宽度 + self._lcd_h = 320 # LCD高度 + + # 调用父类初始化 + super().__init__(self) + +# 创建LCD实例 +lcd = MyLCD() +``` +### 2. 基本绘图操作 +```python +# 清屏为白色 +lcd.Clear(0xFFFF) + +# 绘制红色矩形 +lcd.DrawRectangle(50, 50, 150, 150, 0xF800) + +# 绘制蓝色圆形 +lcd.DrawCircle(120, 160, 50, 0x001F) + +# 绘制绿色对角线 +lcd.DrawLine(0, 0, 239, 319, 0x07E0) +``` +3. 文字显示 +```python +# 显示ASCII字符串 +lcd.ShowAsciiStr(10, 10, 8, 16, "Hello World!", 0x0000, 0xFFFF) + +# 显示汉字 +lcd.lcd_show_chinese_str(10, 30, 16, 16, "中文测试", 0x0000, 0xFFFF) +``` + +## API接口说明 + +**`DrawPoint(x, y, color)`** + +在指定位置绘制一个点。 + +​**​参数说明:​​** + +- x: X坐标 +- y: Y坐标 +- color: RGB565颜色值 + +**`Clear(color)`** + +使用指定颜色清屏。 + +​​**参数说明:​** + +- color: RGB565颜色值 + +**`Fill(x_s, y_s, x_e, y_e, color)`** + +填充指定矩形区域。 + +**​​参数说明:​​** + +- x_s: 起始X坐标 +- y_s: 起始Y坐标 +- x_e: 结束X坐标 +- y_e: 结束Y坐标 +- color: RGB565颜色值 + +**`DrawLine(x0, y0, x1, y1, color)`** + +绘制直线。 + +​​**参数说明:** + +- x0, y0: 起点坐标 +- x1, y1: 终点坐标 +- color: RGB565颜色值 + +**`DrawRectangle(x0, y0, x1, y1, color)`** + +绘制矩形边框。 + +​**​参数说明:** + +- x0, y0: 左上角坐标 +- x1, y1: 右下角坐标 +- color: RGB565颜色值 + +**`DrawCircle(x0, y0, r, color)`** + +绘制圆形。 + +​**​参数说明:​​** + +- x0, y0: 圆心坐标 +- r: 半径 +- color: RGB565颜色值 + +**`ShowChar(x, y, xsize, ysize, ch_buf, fc, bc)`** + +显示单个字符(支持汉字和ASCII)。 + +​**​参数说明:​​** + +- x, y: 显示位置 +- xsize, ysize: 字符尺寸 +- ch_buf: 字符点阵数据 +- fc: 前景色(RGB565) +- bc: 背景色(RGB565) + +**`ShowAscii(x, y, xsize, ysize, ch, fc, bc)`** + +显示ASCII字符。 + +​​**参数说明:** + +- x, y: 显示位置 +- xsize, ysize: 字符尺寸 +- ch: ASCII字符 +- fc: 前景色(RGB565) +- bc: 背景色(RGB565) + +**`ShowAsciiStr(x, y, xsize, ysize, str_ascii, fc, bc)`** + +显示ASCII字符串。 + +​**​参数说明:​​** + +- x, y: 起始位置 +- xsize, ysize: 字符尺寸 +- str_ascii: ASCII字符串 +- fc: 前景色(RGB565) +- bc: 背景色(RGB565) + +**`ShowJpg(name, start_x, start_y)`** + +显示JPG图片。 + +**​​参数说明:** + +- name: 图片文件名 +- start_x, start_y: 显示位置 + +**`lcd_show_chinese(x, y, xsize, ysize, ch, fc, bc)`** + +显示单个汉字。 + +​​**参数说明:** + +- x, y: 显示位置 +- xsize, ysize: 字符尺寸 +- ch: 汉字字符 +- fc: 前景色(RGB565) +- bc: 背景色(RGB565) + +**`lcd_show_chinese_str(x, y, xsize, ysize, str_ch, fc, bc)`** + +显示汉字字符串。 + +​**​参数说明:** + +- x, y: 起始位置 +- xsize, ysize: 字符尺寸 +- str_ch: 汉字字符串 +- fc: 前景色(RGB565) +- bc: 背景色(RGB565) + +**`lcd_show_image(image_data, x, y, width, height)`** + +显示RGB数据图片。 + +​**​参数说明:​​** + +- image_data: RGB565格式图片数据 +- x, y: 显示位置 +- width, height: 图片尺寸 + +**`lcd_show_image_file(path, x, y, width, height, h)`** + +显示图片文件(支持大图分段显示)。 + +​**​参数说明:** + +- path: 图片文件路径 +- x, y: 显示位置 +- width, height: 图片尺寸 +- h: 分段高度(建议满足 widthh2 < 4096) + +**`get_rgb565_color(r, g, b)`** + +RGB888转RGB565颜色转换。 + +​​**参数说明:** + +- r: 红色分量 (0-255) +- g: 绿色分量 (0-255) +- b: 蓝色分量 (0-255) + +​**​返回值:** + +- RGB565颜色值 + +## 应用示例 +创建数字时钟界面 +```python +def digital_clock(lcd): + # 清屏为深蓝色 + lcd.Clear(0x0019) + + # 绘制时钟外框 + lcd.DrawRectangle(50, 50, 190, 110, 0xFFFF) + lcd.Fill(51, 51, 189, 109, 0x0000) + + # 显示时间标签 + lcd.ShowAsciiStr(60, 60, 8, 16, "TIME:", 0xFFFF, 0x0000) + + # 更新时间显示 + while True: + # 获取当前时间 + current_time = "12:34:56" + + # 清除旧时间 + lcd.Fill(100, 60, 180, 75, 0x0000) + + # 显示新时间 + lcd.ShowAsciiStr(100, 60, 16, 24, current_time, 0xFFFF, 0x0000) + + utime.sleep(1) + +# 使用示例 +lcd = MyLCD() +digital_clock(lcd) +``` + + +显示传感器数据仪表盘 +```python +def sensor_dashboard(lcd, temp, humi, press): + # 清屏 + lcd.Clear(0xFFFF) + + # 显示标题 + lcd.lcd_show_chinese_str(80, 10, 24, 24, "环境监测", 0x0000, 0xFFFF) + + # 温度显示 + lcd.lcd_show_chinese_str(30, 50, 16, 16, "温度:", 0x0000, 0xFFFF) + lcd.ShowAsciiStr(80, 50, 16, 24, "{:.1f}°C".format(temp), 0xF800, 0xFFFF) + + # 湿度显示 + lcd.lcd_show_chinese_str(30, 90, 16, 16, "湿度:", 0x0000, 0xFFFF) + lcd.ShowAsciiStr(80, 90, 16, 24, "{:.1f}%".format(humi), 0x001F, 0xFFFF) + + # 压力显示 + lcd.lcd_show_chinese_str(30, 130, 16, 16, "气压:", 0x0000, 0xFFFF) + lcd.ShowAsciiStr(80, 130, 16, 24, "{:.1f}hPa".format(press), 0x07E0, 0xFFFF) + + # 绘制分隔线 + lcd.DrawLine(20, 170, 220, 170, 0x0000) + + # 状态指示 + status = "正常" if 18 <= temp <= 28 and 40 <= humi <= 60 else "异常" + color = 0x07E0 if status == "正常" else 0xF800 + lcd.lcd_show_chinese_str(80, 190, 16, 16, "状态:{}".format(status), color, 0xFFFF) + +# 使用示例 +sensor_dashboard(lcd, 25.5, 45.2, 1013.2) +``` + +## 常见问题排查 +- 检查坐标是否超出屏幕范围 +- 确保图片数据是RGB565格式 +- 使用转换工具预处理图片 \ No newline at end of file diff --git a/libraries/gl5516/README.md b/libraries/gl5516/README.md index 2760be6..6550493 100644 --- a/libraries/gl5516/README.md +++ b/libraries/gl5516/README.md @@ -36,14 +36,14 @@ ldr_sensor = Gl5516(adc_device, ADC.ADC0) ```python resistance = ldr_sensor.read() -print(f"Photoresistor resistance: {resistance}Ω") +print("Photoresistor resistance: {}Ω".format(resistance)) ``` #### Read Raw Voltage Value ```python voltage = ldr_sensor.read_volt() -print(f"Raw voltage: {voltage}mV") +print("Raw voltage: {}mV".format(voltage)) ``` ## API Reference @@ -89,7 +89,7 @@ while True: resistance = ldr.read() voltage = ldr.read_volt() - print(f"Light Level - Resistance: {resistance}Ω, Voltage: {voltage}mV") + print("Light Level - Resistance: {}Ω, Voltage: {}mV".format(resistance, voltage)) if resistance > 10000: # Dark condition print("Dark environment detected") diff --git a/libraries/gl5516/README_zh.md b/libraries/gl5516/README_zh.md index 2c8b2aa..3aa9e15 100644 --- a/libraries/gl5516/README_zh.md +++ b/libraries/gl5516/README_zh.md @@ -36,14 +36,14 @@ ldr_sensor = Gl5516(adc_device, ADC.ADC0) ```python resistance = ldr_sensor.read() -print(f"光敏电阻阻值: {resistance}Ω") +print("光敏电阻阻值: {}Ω".format(resistance)) ``` #### 读取原始电压值 ```python voltage = ldr_sensor.read_volt() -print(f"原始电压值: {voltage}mV") +print("原始电压值: {}mV".format(voltage)) ``` ## API接口说明 @@ -89,7 +89,7 @@ while True: resistance = ldr.read() voltage = ldr.read_volt() - print(f"光照强度 - 电阻值: {resistance}Ω, 电压值: {voltage}mV") + print("光照强度 - 电阻值: {}Ω, 电压值: {}mV".format(resistance, voltage)) if resistance > 10000: # 黑暗环境 print("检测到黑暗环境") diff --git a/libraries/gl5528/README.md b/libraries/gl5528/README.md index 82002a8..472dac9 100644 --- a/libraries/gl5528/README.md +++ b/libraries/gl5528/README.md @@ -37,14 +37,14 @@ ldr_sensor = Gl5528(adc_device, ADC.ADC0) ```python resistance, lux = ldr_sensor.read() -print(f"Photoresistor resistance: {resistance}Ω, Illuminance: {lux}lux") +print("Photoresistor resistance: {}Ω, Illuminance: {}lux".format(resistance, lux)) ``` #### Read Raw Voltage Value ```python voltage = ldr_sensor.read_volt() -print(f"Raw voltage: {voltage}mV") +print("Raw voltage: {}mV".format(voltage)) ``` ## API Reference @@ -104,9 +104,9 @@ while True: resistance, lux = ldr.read() if lux: - print(f"Current environment - Resistance: {resistance}Ω, Illuminance: {lux}lux") + print("Current environment - Resistance: {}Ω, Illuminance: {}lux".format(resistance, lux)) else: - print(f"Current environment - Resistance: {resistance}Ω (Out of measurement range)") + print("Current environment - Resistance: {}Ω (Out of measurement range)".format(resistance)) # Light-dependent control logic if lux and lux > 500: diff --git a/libraries/gl5528/README_zh.md b/libraries/gl5528/README_zh.md index afb7f74..9219b21 100644 --- a/libraries/gl5528/README_zh.md +++ b/libraries/gl5528/README_zh.md @@ -37,14 +37,14 @@ ldr_sensor = Gl5528(adc_device, ADC.ADC0) ```python resistance, lux = ldr_sensor.read() -print(f"光敏电阻阻值: {resistance}Ω, 光照度: {lux}lux") +print("光敏电阻阻值: {}Ω, 光照度: {}lux".format(resistance, lux)) ``` #### 读取原始电压值 ```python voltage = ldr_sensor.read_volt() -print(f"原始电压值: {voltage}mV") +print("原始电压值: {}mV".format(voltage)) ``` ## API接口说明 @@ -104,9 +104,9 @@ while True: resistance, lux = ldr.read() if lux: - print(f"当前环境 - 电阻值: {resistance}Ω, 光照度: {lux}lux") + print("当前环境 - 电阻值: {}Ω, 光照度: {}lux".format(resistance, lux)) else: - print(f"当前环境 - 电阻值: {resistance}Ω (超出测量范围)") + print("当前环境 - 电阻值: {}Ω (超出测量范围)".format(resistance)) # 根据光照度控制逻辑 if lux and lux > 500: diff --git a/libraries/keyscan/README-zh.md b/libraries/keyscan/README-zh.md deleted file mode 100644 index c0f6a01..0000000 --- a/libraries/keyscan/README-zh.md +++ /dev/null @@ -1,43 +0,0 @@ -Key 按键驱动模块 - -**类引用:** -```python -from key_driver import Key -``` - -**实例化参数:** - -|名称| 必填| 类型| 说明| -|----|----|----|----| -|pin | 是 | int | GPIO引脚号 | -| work_mode | 是 | int| 工作模式:Key.WorkMode.ONE_SHOT 或 Key.WorkMode.CONTINUOUS | -| debounse_ms | 是 |int| 按键消抖时间(毫秒)| -| level_on_pressed | 是 | int 按键按下时的电平(0或1)| -| cared_event | 是 | int | 关心的事件类型(Key.Event.PRESSED、Key.Event.RELEASED 或其组合)| -| event_cb | 是 | function | 事件回调函数 | -| long_press_event | 否 | list |长按事件时间列表(秒)| - -**事件类型:** - -| 名称 | 值 | 说明 | -|----|----|----| -| Key.Event.PRESSED| 0x01| 按键按下事件| -|Key.Event.RELEASED |0x02| 按键释放事件| -|Key.Event.LONG_PRESSED| 0x04| 长按事件| - -**工作模式:** - -| 名称| 值 | 说明| -|----|----|----| -|Key.WorkMode.ONE_SHOT| 0x01| 单次触发模式| -|Key.WorkMode.CONTINUOUS| 0x02| 连续触发模式| - -**方法:** - -l disable() - -禁用按键中断检测。 - -l enable() - -启用按键中断检测。 \ No newline at end of file diff --git a/libraries/keyscan/README.md b/libraries/keyscan/README.md index 0a2b898..a07c352 100644 --- a/libraries/keyscan/README.md +++ b/libraries/keyscan/README.md @@ -1,46 +1,129 @@ -Key button driver module +# Keyboard Driver Module Documentation +## Overview -**Class Reference:** +This document explains how to use the key driver module to implement various key detection functions, including single-key press, continuous key detection, short press/long press recognition, etc. The driver achieves efficient key detection through the interrupt mechanism and supports the management of multiple keys simultaneously and the handling of complex events. +## Key Features + +- Supports single-key press detection and continuous-key press detection modes +- Supports independent handling of key press/release events +- Supports long-key recognition (with customizable long-press duration) +- Built-in hardware debouncing mechanism +- Efficient event handling through interrupt-driven approach +- Parallel management of multiple keys +- Thread-safe callback mechanism + +## Quick Start +### 1. Import Required Modules ```python +from machine import Pin from key_driver import Key ``` +### 2. Define the key event handling function +```python +def key_event_handler(key, event): + if event == Key.Event.PRESSED: + print("The button with pin number {} has been pressed".format(key.pin)) + elif event == Key.Event.RELEASED: + print("The button with pin {} was released for a duration of {} seconds.".format(key.pin, key.sec)) + elif event == Key.Event.LONG_PRESSED: + print("Press key {} for {} seconds".format(key.pin, key.sec)) +``` +### 3. Initialize the key object +```python +# Configure K1 button (GPIO4) +# Working mode: Continuous detection +# Decoupling time: 20ms +# Pressing level: Low level (0) +# Attention event: Press and release +k1 = Key( + pin=Pin.GPIO4, + work_mode=Key.WorkMode.CONTINUOUS, + debounse_ms=20, + level_on_pressed=0, + cared_event=Key.Event.PRESSED | Key.Event.RELEASED, + event_cb=key_event_handler +) +``` +### 4. Run the main program +```python +while True: + # Main Program Logic + sleep_ms(100) +``` + +## API Interface Description +**`Key(pin, work_mode, debounse_ms, level_on_pressed, cared_event, event_cb, long_press_event=[])`** -**Instantiation Parameters:** -| Name | Required | Type | Description | -|----|----|----|----| -| pin | is | int | GPIO pin number | -| work_mode | is | int | Working mode: Key.WorkMode.ONE_SHOT or Key.WorkMode.CONTINUOUS | -| debounce_ms | is | int | Debouncing time for the key press (in milliseconds) | -| level_on_pressed | is | int | Level when the key is pressed (0 or 1) | -| cared_event | is | int | Type of event to be cared about (Key.Event.PRESSED, Key.Event.RELEASED or their combination) | -| event_cb | is | function | Event callback function | -| long_press_event | is | list | List of long press event times (in seconds) | +Construct the constructor to initialize the key object. -**Event Type:** +**Parameter Description:** -| Name | Value | Description | -|----|----|----| -| Key.Event.PRESSED | 0x01 | Key Pressed Event | -| Key.Event.RELEASED | 0x02 | Key Released Event | -| Key.Event.LONG_PRESSED | 0x04 | Long Press Event | +- pin: GPIO pin number +- work_mode: Working mode + - Key.WorkMode.ONE_SHOT: Single-shot key mode + - Key.WorkMode.CONTINUOUS: Continuous detection mode +- debounce_ms: Debouncing time (milliseconds) +- level_on_pressed: Voltage level when the key is pressed + - 0: Pressed state is low voltage + - 1: Pressed state is high voltage +- cared_event: Combinations of events to be monitored + - Key.Event.PRESSED: Key pressed event + - Key.Event.RELEASED: Key released event + - Key.Event.LONG_PRESSED: Long press event +- event_cb: Key event callback function +- long_press_event: Long press time settings (list of seconds) -**Work Mode:** +**`disable()`** -| Name | Value | Description | -|----|----|----| -| Key.WorkMode.ONE_SHOT | 0x01 | One-shot trigger mode | -| Key.WorkMode.CONTINUOUS | 0x02 | Continuous trigger mode | -**Method:** +Disable key detection. -l disable() +**`enable()`** -Disable the key interrupt detection. +Enable key detection. -l enable() +## Application Example +Basic Key Press Detection +```python +def key_handler(key, event): + if event == Key.Event.PRESSED: + print("Button pressed") + elif event == Key.Event.RELEASED: + print("Button released") +# Initialize key K1 +Key( + pin=Pin.GPIO4, + work_mode=Key.WorkMode.CONTINUOUS, + debounse_ms=20, + level_on_pressed=0, + cared_event=Key.Event.PRESSED | Key.Event.RELEASED, + event_cb=key_handler +) +``` +Long press function implementation +```python +def long_press_handler(key, event): + if event == Key.Event.LONG_PRESSED: + print("Long press function triggered. Duration: {} seconds".format(key.sec)) + if key.sec >= 5: + print("Execute factory reset" ) -Enable key interrupt detection. \ No newline at end of file +# Configure the events for long press for 2 seconds and 5 seconds +Key( + pin=Pin.GPIO5, + work_mode=Key.WorkMode.CONTINUOUS, + debounse_ms=20, + level_on_pressed=0, + cared_event=Key.Event.PRESSED | Key.Event.RELEASED | Key.Event.LONG_PRESSED, + event_cb=long_press_handler, + long_press_event = [2, 5] # Set the long press points to 2 seconds and 5 seconds. +) +``` +## Common Issues Troubleshooting +- Physical connection problem +- Severe jitter interference +- Incorrect handling of event callbacks \ No newline at end of file diff --git a/libraries/keyscan/README_zh.md b/libraries/keyscan/README_zh.md new file mode 100644 index 0000000..451747f --- /dev/null +++ b/libraries/keyscan/README_zh.md @@ -0,0 +1,123 @@ +# 按键驱动模块文档 +## 概述 + +本文档介绍如何使用按键驱动模块实现各类按键检测功能,包括单次按键、连续检测按键、短按/长按识别等。该驱动通过中断机制实现高效按键检测,支持多按键同时管理和复杂事件处理。 +## 主要特性 + +- 支持单次按键检测和连续按键检测模式 +- 支持按键按下/释放事件独立处理 +- 支持长按键识别(可自定义长按时间) +- 内置硬件消抖机制 +- 中断驱动的高效事件处理 +- 多按键并行管理 +- 线程安全的回调机制 + +## 快速入门 +### 1. 导入所需模块 +```python +from machine import Pin +from key_driver import Key +``` +### 2. 定义按键事件处理函数 +```python +def key_event_handler(key, event): + if event == Key.Event.PRESSED: + print("按键{}被按下".format(key.pin)) + elif event == Key.Event.RELEASED: + print("按键{}释放,持续 {} 秒".format(key.pin, key.sec)) + elif event == Key.Event.LONG_PRESSED: + print("按键{}长按 {} 秒".format(key.pin, key.sec)) +``` +### 3. 初始化按键对象 +```python +# 配置K1按键 (GPIO4) +# 工作模式: 连续检测 +# 消抖时间: 20ms +# 按下电平: 低电平(0) +# 关注事件: 按下和释放 +k1 = Key( + pin=Pin.GPIO4, + work_mode=Key.WorkMode.CONTINUOUS, + debounse_ms=20, + level_on_pressed=0, + cared_event=Key.Event.PRESSED | Key.Event.RELEASED, + event_cb=key_event_handler +) +``` +### 4. 运行主程序 +```python +while True: + # 主程序逻辑 + sleep_ms(100) +``` +## API接口说明 +**`Key(pin, work_mode, debounse_ms, level_on_pressed, cared_event, event_cb, long_press_event=[])`** + +构造函数,初始化按键对象。 + +​**​参数说明:** + +- pin: GPIO引脚号 +- work_mode: 工作模式 + - Key.WorkMode.ONE_SHOT: 单次按键模式 + - Key.WorkMode.CONTINUOUS: 连续检测模式 +- debounse_ms: 消抖时间(毫秒) +- level_on_pressed: 按键按下时的电平 + - 0: 按下为低电平 + - 1: 按下为高电平 +- cared_event: 关注的事件类型组合 + - Key.Event.PRESSED: 按键按下事件 + - Key.Event.RELEASED: 按键释放事件 + - Key.Event.LONG_PRESSED: 长按事件 +- event_cb: 按键事件回调函数 +- long_press_event: 长按时间设置(秒列表) + +**`disable()`** + +禁用按键检测。 +**`enable()`** + +启用按键检测。 + +## 应用示例 +基本按键检测 +```python +def key_handler(key, event): + if event == Key.Event.PRESSED: + print("按键按下") + elif event == Key.Event.RELEASED: + print("按键释放") + +# 初始化按键K1 +Key( + pin=Pin.GPIO4, + work_mode=Key.WorkMode.CONTINUOUS, + debounse_ms=20, + level_on_pressed=0, + cared_event=Key.Event.PRESSED | Key.Event.RELEASED, + event_cb=key_handler +) +``` +长按功能实现 +```python +def long_press_handler(key, event): + if event == Key.Event.LONG_PRESSED: + print("长按功能触发,持续 {} 秒".format(key.sec)) + if key.sec >= 5: + print("执行恢复出厂设置") + +# 配置长按2秒和5秒事件 +Key( + pin=Pin.GPIO5, + work_mode=Key.WorkMode.CONTINUOUS, + debounse_ms=20, + level_on_pressed=0, + cared_event=Key.Event.PRESSED | Key.Event.RELEASED | Key.Event.LONG_PRESSED, + event_cb=long_press_handler, + long_press_event=[2, 5] # 设置2秒和5秒长按点 +) +``` +## 常见问题排查 +- 物理连接问题 +- 抖动干扰严重 +- 事件回调未正确处理 \ No newline at end of file