chore: migrate project into clean repository

This commit is contained in:
yuuux
2026-08-13 16:50:52 +08:00
commit d1d25a09e7
27405 changed files with 9422808 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
cmake_minimum_required(VERSION 3.13)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
find_package(listenai-cmake REQUIRED HINTS $ENV{ARCS_BASE})
project(arcs)
listenai_include_directories(${CMAKE_CURRENT_SOURCE_DIR})
add_subdirectory(src)
listenai_add_executable(${PROJECT_NAME})

View File

@@ -0,0 +1,34 @@
osource "$ARCS_BASE/Kconfig"
config IMAGE_WIDTH
int "iamge width"
default 320
config IMAGE_HEIGHT
int "image height"
default 240
config IMAGE_FORMAT
int "image format, 2:yuyv422 0:rgb565"
default 2
config FACE_LIVE_DETECT_ENABLE
bool "face live detect enable"
default y
config FACE_LIVE_DETECT_THRESHOLD
int "face live detect threshold"
depends on FACE_LIVE_DETECT_ENABLE
range 0 100
default 50
config FACE_COMPARE_SCORE_THRESHOLD
int "face compare score threshold"
range 0 100
default 90
config ONLY_FACE_REGISTER
bool "only face register"
default y
osource "src/button/Kconfig"

View File

@@ -0,0 +1,304 @@
# 人脸识别演示
## 功能说明
本演示是一个完整的人脸识别应用,集成了摄像头图像采集、人脸检测、活体检测、特征提取、人脸识别和可视化显示等功能。用户可通过按键来体验人脸注册和人脸识别的功能。
## 系统架构
```
┌─────────────┐
│ 摄像头模块 │ GC0328 采集图像 (320x240)
└─────────────┘
│
├──────────────────────────────────┐
│ │
│ (实时图像) │ (部分图像)
▼ ▼
┌─────────────┐ ┌────────────────────────┐
│ 显示模块 │ │ 人脸识别算法模块 (AP) │
│ (ST7789 LCD) │◄────────────────│ 检测/对齐/活体/特征/对比 │
└─────────────┘ (人脸结果) └────────────────────────┘
▲ ▲
│ │
│ │ (控制命令)
│ (显示控制) │
│ │
┌─────────────┐ │
│ 按键模块 │───────────────────────────┘
│ (ADC 检测) │ K1:人脸注册
└─────────────┘
```
## 主要功能
#### 1. 实时图像采集
- GC0328 摄像头通过 DVP 接口连续采集 320x240 分辨率图像
- 支持输出 YUYV422彩色模式、YUYV422灰度模式(其中Cb=0, Cr=0)、RGB565模式,最大支持640*480分辨率
- 输出的每帧图片实时发给显示屏显示,同时部分图片也通过 IPC 自动发送到 AP 核进行算法处理
#### 2. 人脸识别算法
人脸识别算法在 AP 核上运行,对每帧图像执行完整的人脸识别流程:
- **人脸检测**:检测图像中的人脸位置和大小,输出人脸矩形框坐标和置信度得分
- **人脸对齐**:定位 68 个人脸关键点(眼睛、鼻子、嘴巴、轮廓等),计算头部姿态角(yaw/pitch/roll)
- **活体检测**:判断人脸是否为真人,输出活体检测结果(0、1)和得分,防止照片、视频攻击
- **特征提取**:提取 384 维人脸特征向量,用于唯一标识一个人脸
- **特征比对**:将提取的特征与已注册人脸进行相似度比对,输出比对得分( 阈值由用户决定,超过阈值则认为是同一人)
目前暂时支持注册最多 10 个人脸特征到内存库,可配置活体检测阈值以适应不同应用场景。
#### 3. 交互式操作
- **K1 键**:抓取当前检测到的人脸特征(需先检测到人脸),如果符合条件(比如活体检测通过、头部姿势正常),就把它存储下来,并且加载到算法对比库中。如果不满足条件,需要用户重新按K1键抓取
#### 4. 可视化显示
- LCD 显示字符来提示用户怎么操作
- LCD 实时显示摄像头采集的画面
- LCD 实时显示人脸检测算法的处理结果,包括检测到的人脸个数、人脸框、活体状态,活体得分等信息;
- 如果已注册有人脸,LCD也会显示检测到人脸的比对得分,超过对比阈值则人脸框显示为绿色(并且显示人脸ID),否则显示为红色
- LCD 显示K1按键的人脸注册个数
## 硬件连接
- **开发板**: ARCS-EVB开发板
- **摄像头**: GC0328 摄像头模块,通过 DVP 接口连接
- **显示屏**: ST7789 LCD 显示屏,通过 SPI 接口连接
- **按键**: 通过 ADC 引脚检测,支持 2 个按键(目前仅K1按键可用)
- **K1**: 注册人脸特征
- **K2**: 人脸识别(与注册人脸比对)(需要CONFIG_ONLY_FACE_REGISTER=n才能生效)
- **调试串口**:
- CP 核 UART0 (PA3),波特率 921600
- AP 核 UART1 (PA21),波特率 921600
## 使用说明
1. 上电后系统自动初始化,LCD 显示摄像头实时画面
2. 检测到人脸时,屏幕显示绿色矩形框
3. **K1 键**: 注册当前人脸特征(最多 10 个)
4. **K2 键**: 触发人脸识别,显示比对得分
5. **K3 键**: 切换摄像头彩色/灰度模式
## 编译运行
```bash
./build.sh -C -DBOARD=arcs_evb
```
## 烧录固件
### 1. 烧录 AP 核固件(Boot Core)
```bash
cskburn -s /dev/ttyACM0 -b 3000000 -C arcs 0x00 ./res/ap.bin
```
### 2. 烧录算法资源到 Flash
```bash
# 人脸检测模型
cskburn -s /dev/ttyACM0 -b 3000000 -C arcs 0x100000 ./res/algo/face_detect_thinker.bin
# 人脸对齐模型
cskburn -s /dev/ttyACM0 -b 3000000 -C arcs 0x170000 ./res/algo/face_align_thinker.bin
# 活体检测模型
cskburn -s /dev/ttyACM0 -b 3000000 -C arcs 0x300000 ./res/algo/face_nir_thinker_lineart_split.bin
# 人脸特征提取模型
cskburn -s /dev/ttyACM0 -b 3000000 -C arcs 0x410000 ./res/algo/face_verify_thinker.bin
```
### 3. 烧录 CP 核固件
```bash
cskburn -s /dev/ttyACM0 -b 3000000 -C arcs 0x800000 ./build/arcs.bin
```
## 预期输出
**CP 核串口输出:**
```
********Arcs SDK 0.1.1 @ v0.0.1-860-gd85bab268324********
Running on hart-id: 1
I/lisa_adc_arcs [00:00:00.035 1 none] ADC0 initialized successfully
I/lisa_i2c_arcs [00:00:00.037 1 none] I2C0 initialized successfully
I/lisa_pwm_arcs [00:00:00.037 1 none] PWM0 initialized successfully (max_channels=8)
I/lisa_touch_cst328 [00:00:00.039 1 none] CST328 touch device initialized successfully
I/lisa_dvp [00:00:00.040 1 none] DVP driver initialized
CP=======! Hard ID: 1
I/main [00:00:00.042 1 main] ic_message_init done!
I/acomp_ipc [00:00:02.044 1 rpc_client] [0]acomp remote dev index 1 name acomp.fd
I/acomp_fd [00:00:02.045 1 main] acomp fd init enter
I/acomp_fd [00:00:02.046 1 main] acomp fd dev index 1,name:acomp.fd
I/acomp_fd [00:00:02.047 1 main] acomp fd dev index 1,name:acomp.fd
I/acomp_fd [00:00:02.049 1 main] acomp fd init exit
I/acomp_fd [00:00:02.050 1 main] acomp fd prepare enter
I/acomp_fd [00:00:02.051 1 main] acomp fd prepare:0x2895ea60, size:128
I/acomp_fd [00:00:02.053 1 main] acomp fd prepare exit
I/acomp_fd [00:00:02.054 1 main] acomp fd start enter
I/acomp_fd [00:00:02.254 1 main] acomp fd start exit
I/acomp_fd [00:00:02.255 1 main] acomp fd add callback enter
I/acomp_fd [00:00:02.256 1 main] acomp fd add callback exit
I/acomp_fd [00:00:02.257 1 main] acomp_fd_live_detect_mode_set enter
I/acomp_fd [00:00:02.259 1 main] acomp_fd_live_detect_mode_set exit
INF:[acomp_stream_channel_create]Acomp stream channel 0x289fcbb4,0x2001b450,'stream.fd_image' created successfully ,vring phy addr=0x28966aa0, num_descs=4, buffer_size=153632, direction=M2R, role=Master
I/acomp_fd [00:00:02.272 1 main] acomp_fd_stream_ch_enable chn(stream.fd_image) index(0),desc(0x2892e280)
I/lvgl_heap [00:00:02.274 1 main] LVGL heap initialized: 1048576 bytes at 0x0x28825800
spi_set_bus_speed: sclk_div = 0 (sclk: 50000000), cs2sclk = 1
I/panel.st7789p3 [00:00:02.536 1 main] ST7789P3 initialized
I/lisa_i2c_arcs [00:00:02.540 1 main] I2C configured: speed=100000 Hz, mode=master
I/lisa_touch_cst328 [00:00:02.541 1 main] I2C auto-configured (speed: 100000 Hz)
I/lisa_touch_cst328 [00:00:02.762 1 main] CST328 hardware reset completed
I/lisa_touch_cst328 [00:00:02.763 1 main] CST328 interrupt pin configured
I/lisa_touch_cst328 [00:00:02.764 1 main] CST328 touch bus attached successfully
I/lisa_touch_cst328 [00:00:02.765 1 main] CST328 read task created with priority 2
I/lisa_touch_cst328 [00:00:02.766 1 main] CST328 interrupt mode enabled
I/lisa_touch_cst328 [00:00:02.767 1 main] CST328 touch device enabled
I/lvgl8_demo_widgets [00:00:02.774 1 task_ui] LVGL screen loaded and started
I/sample [00:00:02.788 1 main] === LISA ADC read example ===
I/sample [00:00:02.789 1 main] adc0 device ready
I/lisa_adc_arcs [00:00:02.790 1 main] Channel 4 configured: ref=1, 10-bit, vref_sel=0, vin_buf=1
I/sample [00:00:02.791 1 main] Channel 4 configured: 3.6V reference, 10-bit resolution
I/btn [00:00:02.793 1 btn] lisa_btn_task enter
I/btn [00:00:02.794 1 main] lisa btn init done
I/video_camera [00:00:02.795 1 main] camera config: w:320, h:240, format:2
I/video_camera [00:00:02.796 1 main] camera device ready
I/video_camera [00:00:02.797 1 main] Setting up camera...
I/lisa_camera [00:00:02.799 1 main] PWDN pin initialized (pin=7)
I/lisa_camera [00:00:02.800 1 main] Enabling XCLK output: 8000000 Hz
I/lisa_i2c_arcs [00:00:02.802 1 main] I2C configured: speed=400000 Hz, mode=master
I/lisa_camera [00:00:02.805 1 main] Sensor detected: PID=0x009D, addr=0x21
I/lisa_camera [00:00:03.308 1 main] Detected sensor frame size: 640x480
I/lisa_camera [00:00:03.311 1 main] Detected sensor pixel format: 0
I/lisa_camera [00:00:03.312 1 main] Frame buffers initialized: count=4, size=614400
I/lisa_camera [00:00:03.313 1 main] Camera setup completed
I/video_camera [00:00:03.314 1 main] Camera capabilities: max_width=640, max_height=480, supported_formats=0x00000005
I/video_camera [00:00:03.316 1 main] crop:x:160, y:120, w:320, h:240
I/lisa_camera [00:00:03.325 1 main] Frame buffers re-initialized: count=4, size=153600
I/lisa_camera [00:00:03.390 1 main] Frame buffers re-initialized: count=4, size=153600
I/video_camera [00:00:03.471 1 main] camera_set_gray on success
I/lisa_dvp [00:00:03.473 1 main] DVP initialized successfully with GPDMA channel 2
I/lisa_dvp [00:00:03.474 1 main] DVP clockout enabled successfully, freq: 8000000 Hz
I/video_camera [00:00:03.476 1 camera_task] Capture task started
I/video_camera [00:00:03.477 1 main] Camera capture started with internal task
I/video_camera [00:00:03.479 1 main] Frame callback registered
I/lisa_dvp [00:00:03.480 1 main] DVP capture started
I/camera_bus_dvp [00:00:03.481 1 main] DVP Normal capture started
I/lisa_camera [00:00:03.482 1 main] Camera started
I/camera_bus_dvp [00:00:03.754 1 isr] dvp_event_callback: event:1
I/camera_bus_dvp [00:00:03.881 1 isr] dvp_event_callback: event:1
I/camera_bus_dvp [00:00:04.008 1 isr] dvp_event_callback: event:1
I/main [00:00:04.102 1 rpc_client] fd result:2732,
I/camera_bus_dvp [00:00:04.135 1 isr] dvp_event_callback: event:1
I/camera_bus_dvp [00:00:04.261 1 isr] dvp_event_callback: event:1
I/main [00:00:04.361 1 rpc_client] fd result:2732,
```
**LCD 屏幕显示:**
- 实时显示摄像头采集的画面
- 实时显示检测到的人脸的黄色方框
- 屏幕左上方会实时显示检测到的人脸个数、活体状态和活体得分
- 按下K1键时,如果检测到人脸符合注册条件,会注册人脸特征,并在屏幕左下角显示"Registered: "个数会增加
- 如果已注册有人脸,LCD也会显示检测到人脸的比对得分,超过对比阈值则人脸框显示为绿色(并且显示人脸ID),否则显示为红色
## 核心 API
| API | 说明 |
|-----|------|
| `acomp_fd_init()` | 初始化人脸识别组件 |
| `acomp_fd_prepare()` | 准备人脸识别算法资源 |
| `acomp_fd_start()` | 启动人脸识别算法 |
| `acomp_fd_add_callback()` | 注册人脸识别结果回调函数 |
| `acomp_fd_live_detect_mode_set()` | 配置活体检测模式 |
| `acomp_fd_stream_ch_enable()` | 使能图像输入数据流通道 |
| `acomp_fd_stream_tx_buffer_alloc()` | 分配发送缓冲区 |
| `acomp_fd_stream_tx_buffer_submit()` | 提交图像数据到算法 |
| `acomp_fd_features_load()` | 导入人脸特征到注册库 |
## 关键代码
```c
/* 1. 初始化 */
acomp_init();
acomp_fd_init();
acomp_fd_prepare();
acomp_fd_start();
acomp_fd_add_callback(FD_CB_EVENT_ENGINE_RLT, fd_event_handler, NULL);
/* 2. 配置活体检测 */
acomp_fd_live_detect_mode_t mode = {.enable = true, .score_threshold = {0.51, 0.1}};
acomp_fd_live_detect_mode_set(&mode);
/* 3. 摄像头回调 - 发送图像到算法 */
void video_camera_cb(uint8_t *data, uint32_t len) {
uint8_t *buffer = acomp_fd_stream_tx_buffer_alloc(0, &buf_size, &desc_idx);
acomp_fd_input_frame_t *frame = (acomp_fd_input_frame_t *)buffer;
frame->format = PIX_FMT_YUV422_YUYV_PACKED;
frame->width = 320; frame->height = 240; frame->length = len;
memcpy(frame->data, data, len);
acomp_fd_stream_tx_buffer_submit(0, buffer, buf_size, desc_idx);
}
/* 4. 结果回调 - 更新显示 */
void fd_event_handler(uint32_t event, void *event_data, uint32_t len, void *priv) {
if (event & FD_CB_EVENT_ENGINE_RLT) {
acomp_fd_result_info_t *info = (acomp_fd_result_info_t *)event_data;
if (info->results_cnt > 0) {
screen_update_fd_info(info, image_data, width, height, len);
}
}
}
```
## 配置说明
### 算法资源地址配置
在 `prj.conf` 中配置算法模型在 Flash 中的地址:
```
CONFIG_ACOMP_FD_RES_FACE_DETECT_ADDRESS=0x30100000
CONFIG_ACOMP_FD_RES_FACE_DETECT_LENGTH=450936
CONFIG_ACOMP_FD_RES_FACE_ALIGN_ADDRESS=0x30170000
CONFIG_ACOMP_FD_RES_FACE_ALIGN_LENGTH=1588664
CONFIG_ACOMP_FD_RES_FACE_LIVE_ADDRESS=0x30300000
CONFIG_ACOMP_FD_RES_FACE_LIVE_LENGTH=1095288
CONFIG_ACOMP_FD_FACE_VERIFY_ADDRESS=0x30410000
CONFIG_ACOMP_FD_FACE_VERIFY_LENGTH=2953752
```
### 摄像头配置
```
CONFIG_IMAGE_WIDTH=320
CONFIG_IMAGE_HEIGHT=240
CONFIG_IMAGE_FORMAT=2 # YUYV422
CONFIG_FACE_LIVE_DETECT_ENABLE=y # 启用活体检测
CONFIG_FACE_LIVE_DETECT_THRESHOLD=50 # 活体检测阈值
CONFIG_FACE_COMPARE_SCORE_THRESHOLD=90 # 人脸比对得分阈值
CONFIG_ONLY_FACE_REGISTER=y # 只注册人脸,后续自动进行人脸识别(不需要用K2按键触发)
```
### PSRAM 堆大小配置
```
CONFIG_PSRAM_HEAP_SIZE=0x680000
```
## 注意事项
1. **算法资源烧录**: 必须先烧录 AP 核固件和 4 个算法模型资源到 Flash,否则人脸识别算法无法正常运行
2. **内存配置**: 人脸识别算法需要较大的 PSRAM 空间,建议配置 `CONFIG_PSRAM_HEAP_SIZE` 不小于 0x680000
3. **摄像头连接**: 确保 GC0328 摄像头正确连接到 DVP 接口,否则无法采集图像
4. **显示屏连接**: 确保 ST7789 LCD 正确连接到 SPI 接口,否则无法显示画面
5. **活体检测阈值**: 活体得分阈值需要根据实际应用场景调整,阈值越高误识率越低但拒识率越高
6. **双核协作**: 本示例运行在 CP 核 (HARTID=1),需要 AP 核 (HARTID=0) 提供算法支持
7. **特征注册**: 最多支持 10 个注册人脸,每个人脸特征为 384 维浮点数
8. **回调函数**: 人脸识别结果通过回调函数异步返回,不要在回调中执行耗时操作

View File

@@ -0,0 +1,177 @@
#!/bin/bash
set -e
usage() {
echo "使用方式: $0 [选项]"
echo "选项:"
echo " -S, --Source <path> 指定项目源码路径 (默认为当前脚本所在目录)"
echo " -t, --target <target> 指定构建目标 (如 menuconfig)"
echo " -C, --Clean 清理构建目录"
echo " -B, --build 构建输出目录"
echo " -h, --help 显示此帮助信息"
echo " -r, --release 以 Release 模式构建 (移除 DEBUG_PATH 信息)"
echo " -w, --warnings-as-errors 将警告视为错误"
echo " -D<var>=<value> 传递 CMake 变量 (可多次使用)"
echo ""
echo "示例:"
echo " $0 -S samples/helloworld -DBOARD=arcs_mini 指定板型构建"
echo " $0 -S samples/helloworld -DBOARD=arcs_evb 使用 EVB 板型"
echo " $0 -S samples/helloworld -t menuconfig -DBOARD=arcs_mini 运行 menuconfig"
echo " $0 -C -S samples/helloworld -DBOARD=arcs_mini 清理并重新构建"
echo " $0 -S samples/helloworld -DBOARD=my_board -DBOARD_SEARCH_PATH=/path/to/boards 使用自定义板型"
exit 1
}
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
PROJECT_PATH="$SCRIPT_DIR"
TARGET=""
CLEAN=false
OUTPUT="build"
WARNINGS_AS_ERRORS=false
RELEASE=false
ARCS_BASE_DIR_NAME="arcs-sdk"
ARCS_DEV_TOOLS_DIR_NAME="listenai-dev-tools"
ARCS_DEV_TOOL_TOOLCHAIN_DIR_NAME="gcc"
ARCS_DEV_TOOL_LISTENAI_TOOLS_DIR_NAME="listenai-tools"
find_arcs_base() {
local current_dir=$(cd "$(dirname "$0")" && pwd)
local dir_name="$ARCS_BASE_DIR_NAME"
while [ "$current_dir" != "/" ]; do
if [ -d "$current_dir/$dir_name" ]; then
echo "Found ARCS_BASE: $current_dir/$dir_name"
export ARCS_BASE="$current_dir/$dir_name"
return 0
fi
current_dir=$(dirname "$current_dir")
done
echo "ARCS_BASE not found, Please add ARCS_BASE environment variable or set ARCS_BASE_DIR_NAME to the correct directory."
echo "Current Target ARCS_BASE directory name: $ARCS_BASE_DIR_NAME."
exit 1
}
find_dev_tools() {
local current_dir=$(cd "$(dirname "$0")" && pwd)
local dir_name="$ARCS_DEV_TOOLS_DIR_NAME"
echo "trying to find $dir_name in parent directories..."
while [ "$current_dir" != "/" ]; do
if [ -d "$current_dir/$dir_name" ]; then
echo "Found $dir_name: $current_dir/$dir_name"
if [ -d "$current_dir/$dir_name/$ARCS_DEV_TOOL_LISTENAI_TOOLS_DIR_NAME" ]; then
echo "Found LISTENAI_TOOLS_PATH: $current_dir/$dir_name/$ARCS_DEV_TOOL_LISTENAI_TOOLS_DIR_NAME"
export LISTENAI_TOOLS_PATH="$current_dir/$dir_name/$ARCS_DEV_TOOL_LISTENAI_TOOLS_DIR_NAME"
fi
if [ -d "$current_dir/$dir_name/$ARCS_DEV_TOOL_TOOLCHAIN_DIR_NAME" ]; then
echo "Found NUCLEI_TOOLCHAIN_PATH: $current_dir/$dir_name/$ARCS_DEV_TOOL_TOOLCHAIN_DIR_NAME"
export NUCLEI_TOOLCHAIN_PATH="$current_dir/$dir_name/$ARCS_DEV_TOOL_TOOLCHAIN_DIR_NAME"
fi
return 0
fi
current_dir=$(dirname "$current_dir")
done
}
while [[ $# -gt 0 ]]; do
case $1 in
-S|--Source)
PROJECT_PATH="$2"
shift 2
;;
-B|--build)
OUTPUT="$2"
shift 2
;;
-t|--target)
TARGET="$2"
shift 2
;;
-C|--Clean)
CLEAN=true
shift 1
;;
-w|--warnings-as-errors)
WARNINGS_AS_ERRORS=true
shift 1
;;
-h|--help)
usage
;;
-r|--release)
RELEASE=true
shift 1
;;
-D*)
CMAKE_VARS+=("$1")
shift 1
;;
*)
echo "未知参数: $1"
usage
;;
esac
done
echo "Source: $PROJECT_PATH"
echo "Target: $TARGET"
echo "Clean : $CLEAN"
if [ -z "$LISTENAI_TOOLS_PATH" ] || [ -z "$NUCLEI_TOOLCHAIN_PATH" ]; then
find_dev_tools
fi
if [ -z "${LISTENAI_TOOLS_PATH}" ]; then
export LISTENAI_TOOLS_PATH="请添加 LISTENAI_TOOLS_PATH 环境变量,或在此行设置正确的路径"
echo "请添加 LISTENAI_TOOLS_PATH 环境变量或者修改脚本后, 注释脚本第 $LINENO 行";exit 1;
fi
if [ -z "${NUCLEI_TOOLCHAIN_PATH}" ]; then
export NUCLEI_TOOLCHAIN_PATH="请添加 NUCLEI_TOOLCHAIN_PATH 环境变量,或在此行设置正确的路径"
echo "请添加 NUCLEI_TOOLCHAIN_PATH 环境变量或者修改脚本后, 注释脚本第 $LINENO 行";exit 1;
fi
############### 下面代码不用修改 ##################
# 构建工具的位置
CMAKE_PROGRAM="$LISTENAI_TOOLS_PATH/cmake/bin/cmake"
NINJA_PROGRAM="$LISTENAI_TOOLS_PATH/ninja/ninja"
# 配置环境变量 ARCS_BASE
if [ -z "$ARCS_BASE" ]; then
find_arcs_base
fi
if [ "$CLEAN" = true ]; then
rm -rf $OUTPUT
fi
# Initialize CMAKE_VARS array if it doesn't exist
declare -a CMAKE_VARS
# Add warnings-as-errors flag if enabled
if [ "$WARNINGS_AS_ERRORS" = true ]; then
CMAKE_VARS+=("-DCMAKE_C_FLAGS=-Werror")
CMAKE_VARS+=("-DCMAKE_CXX_FLAGS=-Werror")
echo "Treating warnings as errors"
fi
# Add release flags if enabled
if [ "$RELEASE" = true ]; then
CMAKE_VARS+=("-DENABLE_DEBUG_PATH=OFF")
echo "Release mode enabled (-DENABLE_DEBUG_PATH=OFF)"
fi
$CMAKE_PROGRAM -B "$OUTPUT" -G Ninja -S "$PROJECT_PATH" \
-DCMAKE_MAKE_PROGRAM="$NINJA_PROGRAM" \
"${CMAKE_VARS[@]}"
if [ -z "$TARGET" ]; then
$CMAKE_PROGRAM --build "$OUTPUT" -j4
else
$CMAKE_PROGRAM --build "$OUTPUT" --target "$TARGET"
fi

View File

@@ -0,0 +1,169 @@
#ifndef __ARCS_MEMAP_HEADER__
#define __ARCS_MEMAP_HEADER__
#define __KB__(x) ((x) * 1024)
#define __MB__(x) ((x) * 1024 * 1024)
#if CONFIG_ARCS_AP_CORE
#define MEM_ILM_BASE 0x00080000
#define MEM_ILM_SIZE (__KB__(16))
#define MEM_DLM_BASE 0x00100000
#define MEM_DLM_SIZE (__KB__(8))
#else
#define MEM_ILM_BASE 0x00280000
#define MEM_ILM_SIZE (__KB__(16))
#define MEM_DLM_BASE 0x00300000
#define MEM_DLM_SIZE (__KB__(8))
#endif
#define MEM_BTRAM_BASE 0x200C0000
#define MEM_BTRAM_SIZE (__KB__(24))
/* FLASH 分配 */
#define MEM_TOTAL_FLASH_SIZE __MB__(16)
#define MEM_AP_FLASH_BASE 0x30000000
#define MEM_AP_FLASH_SIZE __KB__(1024)
#define MEM_CP_FLASH_BASE (0x30000000 + __MB__(8))
#define MEM_CP_FLASH_SIZE __MB__(8)
/* PSRAM 分配 */
#define MEM_AP_PSRAM_BASE 0x28000000
#define MEM_AP_PSRAM_SIZE __MB__(8)
#define MEM_CP_PSRAM_BASE ((MEM_AP_PSRAM_BASE) + (MEM_AP_PSRAM_SIZE))
#define MEM_CP_PSRAM_SIZE __MB__(8)
#if CONFIG_ARCS_AP_CORE
#define MEM_PSRAM_BASE MEM_AP_PSRAM_BASE
#define MEM_PSRAM_SIZE MEM_AP_PSRAM_SIZE
#else
#define MEM_PSRAM_BASE MEM_CP_PSRAM_BASE
#define MEM_PSRAM_SIZE MEM_CP_PSRAM_SIZE
#endif
#if CONFIG_ARCS_AP_CORE
#define MEM_FLASH_BASE MEM_AP_FLASH_BASE
#define MEM_FLASH_SIZE MEM_AP_FLASH_SIZE
#else
#define MEM_FLASH_BASE MEM_CP_FLASH_BASE
#define MEM_FLASH_SIZE MEM_CP_FLASH_SIZE
#endif
#define __MEM_TOTAL_SRAM_START__ 0x20000080 //暂留128(0x80)字节给WiFi硬件
#define __MEM_TOTAL_SRAM_END__ 0x20050000
/**
* SRAM 应用侧分配
* --------------------------------------------
* 0x20000000 | CP-WIFI-RAM(这段内存必须在 0x20000000 + 256KB区间)
* | |
* (256K) | CP-SRAM(128K)
* | | AP-SRAM(64KB)
* | |
* | | AP-WIFI-RAM (这段内存必须在 0x20000000 + 256KB区间)
* -------------- |
* 0x20040000 | 接在CP核上的SRAM(总计64K)
* (8K) | IPC共享内存
* (28K) | LUNA CODE & DATA
* -------------- |
* 0x20048800 | 接在AP核上的SRAM(暂时没用)
* | |
* --------------------------------------------
* 0x20050000 | AP算法使用(HardCode)
* | |
* (384K) | ALGO
* | |
* --------------------------------------------
* 0x200B0000 |
* | |
* (24K) | LUNA 核专属内存
* | |
* --------------------------------------------
* 0x200C0000
*/
/* 独立给算法使用 */
#define MEM_APRAM_BASE 0x20050000
#define MEM_APRAM_SIZE (__KB__(384))
/* 注意,修改以下内存时, 必须与CP保持同步修改 */
#define MEM_CP_WIFI_RAM_BASE __MEM_TOTAL_SRAM_START__
#define MEM_CP_WIFI_RAM_SIZE (__KB__(64) - 128) //暂留128(0x80)字节给WiFi硬件
#define MEM_CP_SRAM_BASE ((MEM_CP_WIFI_RAM_BASE) + (MEM_CP_WIFI_RAM_SIZE))
#define MEM_CP_SRAM_SIZE (__KB__(128))
#define MEM_AP_SRAM_BASE ((MEM_CP_SRAM_BASE) + (MEM_CP_SRAM_SIZE))
#define MEM_AP_SRAM_SIZE (__KB__(64))
#define MEM_AP_WIFI_RAM_BASE ((MEM_AP_SRAM_BASE) + (MEM_AP_SRAM_SIZE))
#define MEM_AP_WIFI_RAM_SIZE (__KB__(0))
#define MEM_IPC_BASE ((MEM_AP_WIFI_RAM_BASE) + (MEM_AP_WIFI_RAM_SIZE))
#define MEM_IPC_SIZE (__KB__(8))
#define MEM_LUNA_BASE ((MEM_IPC_BASE) + (MEM_IPC_SIZE))
#define MEM_LUNA_SIZE (__KB__(28))
// #define MEM_AP_SRAM_BASE ((MEM_LUNA_BASE) + (MEM_LUNA_SIZE))
// #define MEM_AP_SRAM_SIZE (__KB__(62))
#if CONFIG_ARCS_CP_CORE
#define MEM_SRAM_BASE MEM_CP_SRAM_BASE
#define MEM_SRAM_SIZE MEM_CP_SRAM_SIZE
#define MEM_WFRAM_BASE MEM_CP_WIFI_RAM_BASE
#define MEM_WFRAM_SIZE MEM_CP_WIFI_RAM_SIZE
#else
#define MEM_SRAM_BASE MEM_AP_SRAM_BASE
#define MEM_SRAM_SIZE MEM_AP_SRAM_SIZE
#define MEM_WFRAM_BASE MEM_AP_WIFI_RAM_BASE
#define MEM_WFRAM_SIZE MEM_AP_WIFI_RAM_SIZE
#endif
/* 检查下内存是否超出 */
#if (MEM_IPC_BASE + MEM_IPC_SIZE) > __MEM_TOTAL_SRAM_END__
#error "mem sram overflow"
#endif
/* wifi sram 必须要在 0x20000000 ~ 0x20040000之间 */
#if (MEM_CP_WIFI_RAM_BASE < 0x20000000) || ((MEM_CP_WIFI_RAM_BASE + MEM_CP_WIFI_RAM_SIZE) > (0x20000000 + __KB__(256)))
#error "cp wifi sram error"
#endif
/* wifi sram 必须要在 0x20000000 ~ 0x20040000之间 */
#if (MEM_AP_WIFI_RAM_BASE < 0x20000000) || ((MEM_AP_WIFI_RAM_BASE + MEM_AP_WIFI_RAM_SIZE) > (0x20000000 + __KB__(256)))
#error "ap wifi sram error"
#endif
/* luna code & instruction & data 必须要在 0x20040000 ~ 0x200B0000 + 448(KB)之间 */
#if (MEM_LUNA_BASE < 0x20040000) || ((MEM_LUNA_BASE + MEM_LUNA_SIZE) > (0x20040000 + __KB__(448)))
#error "ap luna sram error"
#endif
/* 根据实际需要调整 */
#if CONFIG_ARCS_AP_CORE
/* 这个是SRAM HEAP大小的定义, 该heap从SRAM中分配 */
#define SRAM_HEAP_SIZE (__KB__(5))
// /* WIFI校准数据大小 */
// #define MEM_WIFI_CALIBRATION_SIZE (__KB__(16))
// #define MEM_WIFI_TRACE_SIZE (__KB__(1))
#define MEM_WIFI_CALIBRATION_SIZE (__KB__(16))
#define MEM_WIFI_TRACE_SIZE (__KB__(0))
#define MEM_WIFI_LA_DUMP_SIZE (__KB__(32))
/* 中断栈 */
#define MEM_INTERRUPT_STACK_SIZE (4 * 1024)
#else
/* 在CP侧, 没有wifi的校准数据与跟踪数据, 这里定义为0 */
#define MEM_WIFI_CALIBRATION_SIZE (__KB__(0))
#define MEM_WIFI_TRACE_SIZE (__KB__(0))
/* 中断栈 */
#define MEM_INTERRUPT_STACK_SIZE (4 * 1024)
#endif
#endif//__ARCS_MEMAP_HEADER__

View File

@@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""
合并多个 bin 文件到一个完整的固件文件
空白区域填充 0xFF(Flash 擦除后的默认值)
"""
import os
import sys
from pathlib import Path
# 固件配置:(地址偏移, bin文件路径)
FIRMWARE_MAP = [
(0x000000, "./res/ap.bin"),
(0x100000, "./res/algo/face_detect_thinker.bin"),
(0x170000, "./res/algo/face_align_thinker.bin"),
(0x300000, "./res/algo/face_nir_thinker_lineart_split.bin"),
(0x410000, "./res/algo/face_verify_thinker.bin"),
(0x800000, "./build/arcs.bin"),
]
# 输出文件配置
OUTPUT_FILE = "./merged_firmware.bin"
FILL_BYTE = 0xFF # 空白区域填充字节(0xFF 或 0x00)
def merge_bins():
"""合并所有 bin 文件"""
# 检查所有输入文件是否存在
print("检查输入文件...")
for offset, filepath in FIRMWARE_MAP:
if not os.path.exists(filepath):
print(f"❌ 错误: 文件不存在: {filepath}")
return False
file_size = os.path.getsize(filepath)
print(f" ✓ 0x{offset:08X}: {filepath} ({file_size} bytes)")
# 计算总固件大小(最后一个文件的结束位置)
last_offset, last_file = FIRMWARE_MAP[-1]
last_size = os.path.getsize(last_file)
total_size = last_offset + last_size
print(f"\n固件总大小: {total_size} bytes ({total_size / 1024 / 1024:.2f} MB)")
# 创建填充的固件缓冲区
print(f"创建固件缓冲区,填充字节: 0x{FILL_BYTE:02X}...")
firmware = bytearray([FILL_BYTE] * total_size)
# 将每个 bin 文件写入对应位置
print("\n合并 bin 文件...")
for offset, filepath in FIRMWARE_MAP:
print(f" 写入 {filepath} 到偏移 0x{offset:08X}...")
with open(filepath, 'rb') as f:
data = f.read()
firmware[offset:offset + len(data)] = data
print(f" ✓ 已写入 {len(data)} bytes")
# 写入输出文件
print(f"\n保存合并后的固件到 {OUTPUT_FILE}...")
with open(OUTPUT_FILE, 'wb') as f:
f.write(firmware)
output_size = os.path.getsize(OUTPUT_FILE)
print(f"✓ 完成! 输出文件大小: {output_size} bytes ({output_size / 1024 / 1024:.2f} MB)")
# 显示固件布局
print("\n固件布局:")
print("=" * 70)
print(f"{'起始地址':<12} {'结束地址':<12} {'大小':<12} {'文件'}")
print("-" * 70)
for i, (offset, filepath) in enumerate(FIRMWARE_MAP):
file_size = os.path.getsize(filepath)
end_offset = offset + file_size
# 显示当前文件
print(f"0x{offset:08X} 0x{end_offset:08X} {file_size:>10} B {filepath}")
# 显示空白区域
if i < len(FIRMWARE_MAP) - 1:
next_offset = FIRMWARE_MAP[i + 1][0]
gap_size = next_offset - end_offset
if gap_size > 0:
print(f"0x{end_offset:08X} 0x{next_offset:08X} {gap_size:>10} B (填充 0x{FILL_BYTE:02X})")
print("=" * 70)
return True
def main():
"""主函数"""
print("=" * 70)
print("固件合并工具")
print("=" * 70)
print()
# 切换到脚本所在目录
script_dir = Path(__file__).parent
os.chdir(script_dir)
print(f"工作目录: {os.getcwd()}\n")
# 执行合并
if merge_bins():
print("\n✓ 固件合并成功!")
print(f"\n烧录命令:")
print(f" cskburn -s /dev/ttyACM0 -b 3000000 -C arcs 0x00 {OUTPUT_FILE}")
return 0
else:
print("\n❌ 固件合并失败!")
return 1
if __name__ == "__main__":
sys.exit(main())

Binary file not shown.

View File

@@ -0,0 +1,130 @@
# 使用自定义内存配置文件和自定义链接脚本
CONFIG_MEM_CONFIG=n
CONFIG_MEM_CONFIG_USE_CUSTOM_FILE=y
# CP core
CONFIG_ARCS_CP_CORE=y
# not boot loader
# CP这里一定不能使能,否则会初始化时钟和PSRAM,和AP冲突
CONFIG_BOOT_HART=n
CONFIG_BOOT=n
# C LIB
CONFIG_LINK_OPTION_NONE_SPECS=y
# HEAP
CONFIG_HEAP_SIZE=0x10000
CONFIG_PSRAM_HEAP_SIZE=0x680000
# CPP
CONFIG_LINK_CPP_RUNTIME_SECTIONS=n
CONFIG_CPP_EXCEPTIONS=n
# Debug
CONFIG_BACK_TRACE=y
# freertos
CONFIG_FREERTOS_STATIC_ALLOCATION_ENABLE=y
# main task
CONFIG_MAIN_TASK_STACK_SIZE=8192
CONFIG_MAIN_TASK_PRIORITY=5
# IPC
CONFIG_ARCS_HAL_LSF=y
CONFIG_IPC_LSF=y
CONFIG_DISK_MEM=n
# CONFIG_ARCS_HAL_IC_MUTEX=n
# GPDMA
CONFIG_ARCS_GPDMA_FULL_INIT=y
# acomp fd
CONFIG_ACOMP=y
CONFIG_ACOMP_FD=y
CONFIG_ACOMP_FD_RES_FACE_DETECT_ADDRESS=0x30100000
CONFIG_ACOMP_FD_RES_FACE_DETECT_LENGTH=450936
CONFIG_ACOMP_FD_RES_FACE_ALIGN_ADDRESS=0x30170000
CONFIG_ACOMP_FD_RES_FACE_ALIGN_LENGTH=1588664
CONFIG_ACOMP_FD_RES_FACE_LIVE_ADDRESS=0x30300000
CONFIG_ACOMP_FD_RES_FACE_LIVE_LENGTH=1095288
CONFIG_ACOMP_FD_FACE_VERIFY_ADDRESS=0x30410000
CONFIG_ACOMP_FD_FACE_VERIFY_LENGTH=2953752
# watchdog
CONFIG_BOOT_WITH_WATCHDOG=y
CONFIG_WATCHDOG_ENABLE=n
CONFIG_WORK_QUEUE=y
# camera
CONFIG_LISA_DEVICE=y
CONFIG_LISA_GPIO_DEVICE=y
CONFIG_LISA_GPIOA=y
CONFIG_LISA_GPIOB=y
CONFIG_LISA_I2C=y
CONFIG_LISA_I2C0=y
CONFIG_LISA_SPI_DEVICE=y
CONFIG_LISA_SPI0=y
CONFIG_LISA_CAMERA_DEVICE=y
CONFIG_LISA_CAMERA_BUS_DVP=y
CONFIG_LISA_CAMERA_SENSOR_GC0328=y
# log
CONFIG_LOG=y
CONFIG_LOG_MODE_ASYNC=n
CONFIG_SYSLOG_PRINTK_REDIRECT=y
CONFIG_SYSLOG_UART_TX_PIN=3
CONFIG_SYSLOG_UART_TX_PIN_FUNC_SEL=2
CONFIG_SYSLOG_UART_PORT=0
CONFIG_SYSLOG_UART_BAUDRATE=921600
# display
CONFIG_LISA_DEVICE=y
CONFIG_LISA_GPIO_DEVICE=y
CONFIG_LISA_GPIOA=y
CONFIG_LISA_GPIOB=y
CONFIG_LISA_PWM=y
CONFIG_LISA_SPI1=y
CONFIG_LISA_DISPLAY_DEVICE=y
CONFIG_LISA_DISPLAY_PANEL_ST7789P3=y
CONFIG_LISA_DISPLAY_CPDMA_ROTATE=n
CONFIG_LISA_DISPLAY_BUS_SPI_4WIRE=y
CONFIG_LISA_DISPLAY_COLOR_INVERT=y
CONFIG_PANEL_ST7789P3_WIDTH=240
CONFIG_PANEL_ST7789P3_HEIGHT=320
CONFIG_PANEL_ST7789P3_X_OFFSET=0
# touch
CONFIG_LISA_TOUCH_DEVICE=y
CONFIG_LISA_I2C=y
CONFIG_LISA_I2C0=y
CONFIG_LISA_TOUCH_ARCS_CST328=y
# lvgl
CONFIG_SDK_MODULE_LVGL8=y
CONFIG_LV_DEMO_SYS_HEAP=y
CONFIG_LV_DRIVER_PIXEL_ALIGN_SIZE=16
CONFIG_LV_USE_DEMO_WIDGETS=y
CONFIG_LV_USE_GPU_CSK_DMA2D=y
CONFIG_LV_DOUBLE_VDB=y
CONFIG_LV_USE_PERF_MONITOR=y
CONFIG_LV_DRIVER_FULL_REFRESH=y
CONFIG_LV_CUSTOM_MONITOR=n
CONFIG_LV_REFR_UNCONDITIONAL_AREA_JOIN=y
CONFIG_LV_DRIVER_ROTATE_270=y
CONFIG_LV_ATTRIBUTE_FAST_MEM_USE_IRAM=y
# button
CONFIG_LISA_ADC=y
CONFIG_BUTTON=y
CONFIG_GPIO_BUTTON=n
CONFIG_ADC_BUTTON=y
CONFIG_ADC_BUTTON_MAX_BUTTON_PER_CHANNEL=3
CONFIG_ADC_BUTTON_SAMPLE_TIMES=1

Binary file not shown.

View File

@@ -0,0 +1,4 @@
tests:
demos.face_detect:
build_only: true

View File

@@ -0,0 +1,16 @@
listenai_library_named(app)
listenai_library_sources(
main.c
)
listenai_include_directories(
${CMAKE_CURRENT_SOURCE_DIR}
)
add_subdirectory(button)
add_subdirectory(adc_key)
add_subdirectory(camera)
add_subdirectory(fd_image_stream)
add_subdirectory(display)
add_subdirectory(screen)

View File

@@ -0,0 +1,10 @@
listenai_library_named(adc_key)
listenai_library_sources(
adc_key.c
adc_sample.c
)
listenai_include_directories(
${CMAKE_CURRENT_SOURCE_DIR}
)

View File

@@ -0,0 +1,37 @@
#include "adc_key.h"
void test_adc_button(button_adc_cb_t cb)
{
button_adc_config_t btn_adc_cfg = {
.unit_id = 0,
.adc_channel = 4, // PB6
};
button_config_t btn_cfg = {
.short_press_time_ms = 1500,
.long_press_time_ms = 2000,
.long_hold_time_ms = 4500,
.press_logic_level = 1,
};
const uint16_t vol[10] = {0, 1115, 1650};
for (int i = 0; i < CONFIG_ADC_BUTTON_MAX_BUTTON_PER_CHANNEL; i++) {
btn_adc_cfg.button_index = i;
if (i == 0) {
btn_adc_cfg.min = (0 + vol[i]) / 2;
} else {
btn_adc_cfg.min = (vol[i - 1] + vol[i]) / 2;
}
if (i == (CONFIG_ADC_BUTTON_MAX_BUTTON_PER_CHANNEL - 1)) {
btn_adc_cfg.max = (vol[i] + 3300) / 2;
} else {
btn_adc_cfg.max = (vol[i] + vol[i + 1]) / 2;
}
button_new_adc_device(&btn_cfg, &btn_adc_cfg, cb);
}
}

View File

@@ -0,0 +1,7 @@
#pragma once
#include <stdbool.h>
#include "button_adc.h"
void test_adc_button(button_adc_cb_t cb);

View File

@@ -0,0 +1,86 @@
/*
* Copyright (c) 2025, LISTENAI
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @file main.c
* @brief LISA ADC 基础读取示例
*
* 本示例演示如何使用 LISA ADC 驱动读取模拟信号:
* 1. 初始化ADC设备
* 2. 配置ADC通道参数(参考电压和分辨率)
* 3. 循环读取ADC通道数值
* 4. 转换为电压值并显示
*/
#define LOG_TAG "sample"
#include <lisa_log.h>
#include <stdbool.h>
#include <stdio.h>
#include "lisa_device.h"
#include "lisa_adc.h"
#include "IOMuxManager.h"
#include "FreeRTOS.h"
#include "task.h"
#define ADC_CHANNEL 4
#define ADC_PIN 6 // GPIOB_06 -> Channel 4
#define ADC_DEVICE "adc0"
static lisa_device_t *adc_dev = NULL;
/*
为满足不同板型示例场景,重定向ADC设备的pinmux配置
*/
#ifdef CONFIG_BOARD_ARCS_EVB
void lisa_adc_pinmux()
{
AON_IOMuxManager_PinConfigure(CSK_IOMUX_PAD_B, ADC_PIN, CSK_AON_IOMUX_FUNC_ALTER3);
}
#endif
int adc_sample_init()
{
LISA_LOGI(LOG_TAG, "=== LISA ADC read example ===\n");
/* 获取ADC设备 */
adc_dev = lisa_device_get(ADC_DEVICE);
if (!lisa_device_ready(adc_dev)) {
LISA_LOGE(LOG_TAG, "Error: %s device not ready\n", ADC_DEVICE);
return -1;
}
LISA_LOGI(LOG_TAG, "%s device ready\n", ADC_DEVICE);
/* 配置ADC通道:使用3.6V参考电压,10-bit分辨率 */
lisa_adc_channel_config_t ch_config = {
.reference = LISA_ADC_REF_VDD_3V6,
.resolution = LISA_ADC_RESOLUTION_10BIT,
};
int ret = lisa_adc_channel_setup(adc_dev, ADC_CHANNEL, &ch_config);
if (ret != 0) {
LISA_LOGE(LOG_TAG, "Error: Failed to configure channel %d (code: %d)\n", ADC_CHANNEL, ret);
return -1;
}
LISA_LOGI(LOG_TAG, "Channel %d configured: 3.6V reference, 10-bit resolution\n", ADC_CHANNEL);
// LISA_LOGI(LOG_TAG, "Start reading ADC channel %d...\n\n", ADC_CHANNEL);
}
int adc_sample_get_channel_value(uint32_t channel)
{
uint16_t raw_value = 0;
uint32_t voltage = 0;
int ret = lisa_adc_read(adc_dev, ADC_CHANNEL, &raw_value);
if (ret == 0) {
/* 转换为电压值 (mV) */
voltage = LISA_ADC_RAW_TO_MV(raw_value, 3600, 10);
LISA_LOGD(LOG_TAG, "Channel %d: raw=0x%04x (%4u), voltage=%4lu mV\n",
ADC_CHANNEL, raw_value, raw_value, voltage);
}
return voltage;
}

View File

@@ -0,0 +1,7 @@
#pragma once
#include <stdint.h>
int adc_sample_init(void);
int adc_sample_get_channel_value(uint32_t channel);

View File

@@ -0,0 +1,20 @@
if(CONFIG_BUTTON)
listenai_library_named(psram_button)
listenai_library_sources(
button.c
button_adc.c
button_gpio.c
FlexibleButton/flexible_button.c
# test/test_gpio_button.c
# test/test_adc_button.c
)
listenai_include_directories(
${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/FlexibleButton
)
endif()

View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018-2019 MurphyZhao <d2014zjt@163.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,325 @@
# FlexibleButton
FlexibleButton 是一个基于标准 C 语言的小巧灵活的按键处理库,支持单击、连击、短按、长按、自动消抖,可以自由设置组合按键,可用于中断和低功耗场景。
该按键库解耦了具体的按键硬件结构,理论上支持轻触按键与自锁按键,并可以无限扩展按键数量。另外,FlexibleButton 使用扫描的方式一次性读取所有所有的按键状态,然后通过事件回调机制上报按键事件。核心的按键扫描代码仅有三行,没错,就是经典的 **三行按键扫描算法**。使用 C 语言标准库 API 编写,也使得该按键库可以无缝兼容任意的处理器平台,并且支持任意 OS 和 non-OS(裸机编程)。
## 获取
### Git 方式
```SHELL
git clone https://github.com/murphyzhao/FlexibleButton.git
```
### RT-Thread menuconfig 方式
```
RT-Thread online packages --->
miscellaneous packages --->
[*] FlexibleButton: Small and flexible button driver --->
[*] Enable flexible button demo
version (latest) --->
```
配置完成后,输入 `pkgs --update` 下载软件包。
## 资源统计
ARMCC -O0 优化的情况下,FlexibleButton 资源占用如下:
- CODE:798 字节
- RO DATA:0
- RW DATA:13 字节
- ZI DATA:0
## 快速体验
FlexibleButton 库中提供了一个测试例程 [`./examples/demo_rtt_iotboard.c`](./examples/demo_rtt_iotboard.c),该例程基于 RT-Thread OS 进行测试,硬件平台选择了 *RT-Thread IoT Board Pandora v2.51* 开发板。当然你可以选择使用其他的 OS,或者使用裸机测试,只需要移除 OS 相关的特性即可。
如果你使用自己的硬件平台,只需要将 FlexibleButton 库源码和例程加入你既有的工程下即可。
## DEMO 程序说明
该示例程序可以直接在 RT-Thread [`stm32l475-atk-pandora`](https://github.com/RT-Thread/rt-thread/tree/master/bsp/stm32/stm32l475-atk-pandora) BSP 中运行,可以在该 BSP 目录下,使用 menuconfig 获取本软件包。
### 确定用户按键
```C
typedef enum
{
USER_BUTTON_0 = 0, // 对应 IoT Board 开发板的 PIN_KEY0
USER_BUTTON_1, // 对应 IoT Board 开发板的 PIN_KEY1
USER_BUTTON_2, // 对应 IoT Board 开发板的 PIN_KEY2
USER_BUTTON_3, // 对应 IoT Board 开发板的 PIN_WK_UP
USER_BUTTON_MAX
} user_button_t;
static flex_button_t user_button[USER_BUTTON_MAX];
```
上述代码定义了 4 个按键,数据结构存储在 `user_button` 数组中。
### 程序入口
```C
int flex_button_main(void)
{
rt_thread_t tid = RT_NULL;
user_button_init();
/* 创建按键扫描线程 flex_btn,线程栈 1024 byte,优先级 10 */
tid = rt_thread_create("flex_btn", button_scan, RT_NULL, 1024, 10, 10);
if(tid != RT_NULL)
{
rt_thread_startup(tid);
}
return 0;
}
/* 使用 RT-Thread 的自动初始化 */
INIT_APP_EXPORT(flex_button_main);
```
如上代码所示,首先使用 `user_button_init();` 初始化用户按键硬件,该步骤将用户按键绑定到 FlexibleButton 库。然后,使用 RT-Thread 的 `INIT_APP_EXPORT` 接口导出为上电自动初始化,创建了一个 “flex_btn” 名字的按键扫描线程,线程里扫描检查按键事件。
### 按键初始化代码
`user_button_init();` 初始化代码如下所示:
```C
static void user_button_init(void)
{
int i;
/* 初始化按键数据结构 */
rt_memset(&user_button[0], 0x0, sizeof(user_button));
/* 初始化 IoT Board 按键引脚,使用 rt-thread PIN 设备框架 */
rt_pin_mode(PIN_KEY0, PIN_MODE_INPUT_PULLUP); /* 设置 GPIO 为上拉输入模式 */
rt_pin_mode(PIN_KEY1, PIN_MODE_INPUT_PULLUP); /* 设置 GPIO 为上拉输入模式 */
rt_pin_mode(PIN_KEY2, PIN_MODE_INPUT_PULLUP); /* 设置 GPIO 为上拉输入模式 */
rt_pin_mode(PIN_WK_UP, PIN_MODE_INPUT_PULLDOWN); /* 设置 GPIO 为下拉输入模式 */
for (i = 0; i < USER_BUTTON_MAX; i ++)
{
user_button[i].id = i;
user_button[i].usr_button_read = common_btn_read;
user_button[i].cb = common_btn_evt_cb;
user_button[i].pressed_logic_level = 0;
user_button[i].short_press_start_tick = FLEX_MS_TO_SCAN_CNT(1500);
user_button[i].long_press_start_tick = FLEX_MS_TO_SCAN_CNT(3000);
user_button[i].long_hold_start_tick = FLEX_MS_TO_SCAN_CNT(4500);
if (i == USER_BUTTON_3)
{
user_button[USER_BUTTON_3].pressed_logic_level = 1;
}
flex_button_register(&user_button[i]);
}
}
```
核心的配置如下:
|配置项|说明|
| :---- | :----|
| id | 按键编号 |
| usr_button_read | 设置按键读值回调函数 |
| cb | 设置按键事件回调函数 |
| pressed_logic_level | 设置按键按下时的逻辑电平 |
| short_press_start_tick | 短按起始 tick,使用 FLEX_MS_TO_SCAN_CNT 宏转化为扫描次数 |
| long_press_start_tick | 长按起始 tick,使用 FLEX_MS_TO_SCAN_CNT 宏转化为扫描次数 |
| long_hold_start_tick | 超长按起始 tick,使用 FLEX_MS_TO_SCAN_CNT 宏转化为扫描次数 |
注意,short_press_start_tick、long_press_start_tick 和 long_hold_start_tick 必须使用 `FLEX_MS_TO_SCAN_CNT` 将毫秒时间转化为扫描次数。
`user_button[i].short_press_start_tick = FLEX_MS_TO_SCAN_CNT(1500);` 表示按键按下开始计时,1500 ms 后按键依旧是按下状态的话,就断定为短按开始。
### 事件处理代码
```C
static void common_btn_evt_cb(void *arg)
{
flex_button_t *btn = (flex_button_t *)arg;
rt_kprintf("id: [%d - %s] event: [%d - %30s] repeat: %d\n",
btn->id, enum_btn_id_string[btn->id],
btn->event, enum_event_string[btn->event],
btn->click_cnt);
if (flex_button_event_read(&user_button[USER_BUTTON_0]) == flex_button_event_read(&user_button[USER_BUTTON_1]) == FLEX_BTN_PRESS_CLICK)
{
rt_kprintf("[combination]: button 0 and button 1\n");
}
}
```
示例代码中,将所有的按键事件回调均绑定到 `common_btn_evt_cb` 函数,在该函数中打印了按键 ID 和按键事件,以及按键连击次数,并演示了如何使用组合按键。
## FlexibleButton 代码说明
### 按键事件定义
按键事件的定义并没有使用 Windows 驱动上的定义,主要是方便嵌入式设备中的应用场景(也可能是我理解的偏差),按键事件定义如下:
```C
typedef enum
{
FLEX_BTN_PRESS_DOWN = 0, // 按下事件
FLEX_BTN_PRESS_CLICK, // 单击事件
FLEX_BTN_PRESS_DOUBLE_CLICK, // 双击事件
FLEX_BTN_PRESS_REPEAT_CLICK, // 连击事件,使用 flex_button_t 中的 click_cnt 断定连击次数
FLEX_BTN_PRESS_SHORT_START, // 短按开始事件
FLEX_BTN_PRESS_SHORT_UP, // 短按抬起事件
FLEX_BTN_PRESS_LONG_START, // 长按开始事件
FLEX_BTN_PRESS_LONG_UP, // 长按抬起事件
FLEX_BTN_PRESS_LONG_HOLD, // 长按保持事件
FLEX_BTN_PRESS_LONG_HOLD_UP, // 长按保持的抬起事件
FLEX_BTN_PRESS_MAX,
FLEX_BTN_PRESS_NONE,
} flex_button_event_t;
```
其中 `FLEX_BTN_PRESS_LONG_HOLD` 事件可以用来实现长按累加的应用场景。
### 按键数据结构
```C
typedef struct flex_button
{
struct flex_button* next;
uint8_t (*usr_button_read)(void *);
flex_button_response_callback cb;
uint16_t scan_cnt;
uint16_t click_cnt;
uint16_t max_multiple_clicks_interval;
uint16_t debounce_tick;
uint16_t short_press_start_tick;
uint16_t long_press_start_tick;
uint16_t long_hold_start_tick;
uint8_t id;
uint8_t pressed_logic_level : 1;
uint8_t event : 4;
uint8_t status : 3;
} flex_button_t;
```
| 序号 | 数据成员 | 是否需要用户初始化 | 说明 |
| :----: | :---- | :----: | :---- |
| 1 | next | 否 | 按键库使用单向链表串起所有的按键 |
| 2 | usr_button_read | 是 | 用户设备的按键引脚电平读取函数,**重要** |
| 3 | cb | 是 | 设置按键事件回调,用于应用层对按键事件的分类处理 |
| 4 | scan_cnt | 否 | 用于记录扫描次数,按键按下是开始从零计数 |
| 5 | click_cnt | 否 | 记录单击次数,用于判定单击、连击 |
| 6 | max_multiple_clicks_interval | 是 | 连击间隙,用于判定是否结束连击计数,有默认值 `MAX_MULTIPLE_CLICKS_INTERVAL` |
| 7 | debounce_tick | 否 | 消抖时间,暂未使用,依靠扫描间隙进行消抖 |
| 8 | short_press_start_tick | 是 | 设置短按事件触发的起始 tick |
| 9 | long_press_start_tick | 是 | 设置长按事件触发的起始 tick |
| 10 | long_hold_start_tick | 是 | 设置长按保持事件触发的起始 tick |
| 11 | id | 是 | 当多个按键使用同一个回调函数时,用于断定属于哪个按键 |
| 12 | pressed_logic_level | 是 | 设置按键按下的逻辑电平。1:标识按键按下的时候为高电平;0:标识按键按下的时候未低电平,**重要** |
| 13 | event | 否 | 用于记录当前按键事件 |
| 14 | status | 否 | 用于记录当前按键的状态,用于内部状态机 |
注意,在使用 `max_multiple_clicks_interval`、`debounce_tick`、`short_press_start_tick`、`long_press_start_tick`、`long_hold_start_tick` 的时候,注意需要使用宏 `**FLEX_MS_TO_SCAN_CNT(ms)**` 将毫秒值转换为扫描次数。因为按键库基于扫描次数运转。示例如下:
```
user_button[1].short_press_start_tick = FLEX_MS_TO_SCAN_CNT(1500); // 1500 毫秒
```
上述代码表示:表示按键按下后开始计时,1500ms 的时候,按键依旧按下,则断定为短按开始,并上报 `FLEX_BTN_PRESS_SHORT_START` 事件。
### 按键注册接口
使用该接口注册一个用户按键,入参为一个 flex_button_t 结构体实例的地址。
```C
int8_t flex_button_register(flex_button_t *button);
```
### 按键事件读取接口
使用该接口获取指定按键的事件。
```C
flex_button_event_t flex_button_event_read(flex_button_t* button);
````
### 按键扫描接口
按键扫描的核心函数,需要放到应用程序中定时扫描,扫描间隔建议 20 毫秒。
```C
void flex_button_scan(void);
```
## 注意事项
- 阻塞问题
因为按键事件回调函数以及按键键值读取函数是在按键扫描的过程中执行的,因此请不要在这类函数中使用阻塞接口,不要进行延时操作。
- 按键扫描函数栈需求
按键扫描函数本身对栈的需求小于 300 字节,但是按键事件回调函数和按键键值读取函数都是在按键扫描函数的上下文中执行的,请格外关心按键事件回调函数与按键键值读取函数对栈空间的需求。
## 其它
### 关于低功耗
本按键库是通过不间断扫描的方式来检查按键状态,因此会一直占用 CPU 资源,这对低功耗应用场景是不友好的。为了降低正常工作模式下的功耗,建议合理配置扫描周期(5ms - 20ms),扫描间隙里 CPU 可以进入轻度睡眠。
该按键库不在底层实现低功耗处理,应用层可以根据自己的功耗模式灵活处理,通常会有以下两种方式:
1. 进入低功耗前,挂起按键扫描线程;退出低功耗后,唤醒按键扫描。
2. 增加按键中断模式,所有的按键中断来,就触发一次按键扫描,以确认所有的按键状态。
> 低功耗相关的探讨参考 [issue 1](https://github.com/murphyzhao/FlexibleButton/issues/1) 中的讨论。
### 关于按键中断模式
由于该按键库一次扫描可以确定所有的按键状态,因此可以将所有的按键中断通过 “**或**” 的方式转化为一个中断,然后在中断处理函数中执行一次按键扫描。
中断 “**或**” 的方式可以通过硬件来完成,也可以通过软件来完成。
硬件方式,需要使用一个 **或门** 芯片,多个输入条件转化为一个输出条件,然后通过一个外部中断即可完成所有按键的中断方式检测。
软件方式,需要为每一个按键配置为中断触发模式,然后在每一个按键中断的中断处理函数中执行按键扫描。
为了在降低中断处理函数中执行按键扫描带来的时延,可以通过信号量的方式来异步处理,仅在中断处理函数中释放一个按键扫描的信号量,然后在按键扫描线程中监测该信号量。
### 关于组合按键
该按键库仅做了底层的按键扫描处理,一次扫描可以确定所有的按键状态,并上报对应的按键事件,如果需要支持组合按键,请再封一层,根据按键库返回的事件封装需要的组合按键。[示例程序](./examples/demo_rtt_iotboard.c)提供了简单的实现。
### 关于矩阵键盘
不管你的矩阵键盘是通过什么通信方式获取按键状态的,只要你将读取按键状态的函数对接到 Flexible_button 数据结构中的 `uint8_t (*usr_button_read)(void*);` 函数上即可。
> 参考 [issue 2](https://github.com/murphyzhao/FlexibleButton/issues/2) 中的讨论。
## 问题和建议
如果有什么问题或者建议欢迎提交 [Issue](https://github.com/murphyzhao/FlexibleButton/issues) 进行讨论。
## 维护
- [MurphyZhao](https://github.com/murphyzhao)
## 感谢
感谢所有一起探讨的朋友,感谢所有使用 flexible_button 的朋友,感谢你们的 Star 和 Fork,谢谢你们的支持。
- 感谢 [BOBBOM](https://github.com/BOBBOM) 发现 flex_button_register 函数中的逻辑问题
- 感谢 [BOBBOM](https://github.com/BOBBOM) 解除 flexible_button 中对按键数量的限制
- 感谢 [**rt-thread**](https://mp.weixin.qq.com/s/HJEcSXhykBq1T5Hx0TdjMw) 的支持
- 感谢 [**电子发烧友**](https://mp.weixin.qq.com/s/mQFyrPAvz_TSktQLrSqQfA) 的支持
- 感谢 [**威驰电子**](https://mp.weixin.qq.com/s/oAwFXPostMFBtb2EGxTdig) 的支持
## 友情链接
- RT-Thread [IoT Board](https://github.com/RT-Thread/IoT_Board) 开发板

View File

@@ -0,0 +1,325 @@
/**
* @File: flexible_button.c
* @Author: MurphyZhao
* @Date: 2018-09-29
*
* Copyright (c) 2018-2019 MurphyZhao <d2014zjt@163.com>
* https://github.com/murphyzhao
* All rights reserved.
* License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Change logs:
* Date Author Notes
* 2018-09-29 MurphyZhao First add
* 2019-08-02 MurphyZhao Migrate code to github.com/murphyzhao account
* 2019-12-26 MurphyZhao Refactor code and implement multiple clicks
*
*/
#include "flexible_button.h"
#ifndef NULL
#define NULL 0
#endif
#define EVENT_SET_AND_EXEC_CB(btn, evt) \
do \
{ \
btn->event = evt; \
if(btn->cb) \
btn->cb((flex_button_t*)btn); \
} while(0)
/**
* BTN_IS_PRESSED
*
* 1: is pressed
* 0: is not pressed
*/
#define BTN_IS_PRESSED(i) (g_btn_status_reg & (1 << i))
enum FLEX_BTN_STAGE
{
FLEX_BTN_STAGE_DEFAULT = 0,
FLEX_BTN_STAGE_DOWN = 1,
FLEX_BTN_STAGE_MULTIPLE_CLICK = 2
};
typedef uint32_t btn_type_t;
static flex_button_t *btn_head = NULL;
/**
* g_logic_level
*
* The logic level of the button pressed,
* Each bit represents a button.
*
* First registered button, the logic level of the button pressed is
* at the low bit of g_logic_level.
*/
btn_type_t g_logic_level = (btn_type_t)0;
/**
* g_btn_status_reg
*
* The status register of all button, each bit records the pressing state of a button.
*
* First registered button, the pressing state of the button is
* at the low bit of g_btn_status_reg.
*/
btn_type_t g_btn_status_reg = (btn_type_t)0;
static uint8_t button_cnt = 0;
/**
* @brief Register a user button
*
* @param button: button structure instance
* @return Number of keys that have been registered, or -1 when error
*/
int32_t flex_button_register(flex_button_t *button)
{
flex_button_t *curr = btn_head;
if (!button || (button_cnt > sizeof(btn_type_t) * 8))
{
return -1;
}
while (curr)
{
if(curr == button)
{
return -1; /* already exist. */
}
curr = curr->next;
}
/**
* First registered button is at the end of the 'linked list'.
* btn_head points to the head of the 'linked list'.
*/
button->next = btn_head;
button->status = FLEX_BTN_STAGE_DEFAULT;
button->event = FLEX_BTN_PRESS_NONE;
button->scan_cnt = 0;
button->click_cnt = 0;
button->max_multiple_clicks_interval = MAX_MULTIPLE_CLICKS_INTERVAL;
btn_head = button;
/**
* First registered button, the logic level of the button pressed is
* at the low bit of g_logic_level.
*/
g_logic_level |= (button->pressed_logic_level << button_cnt);
button_cnt ++;
return button_cnt;
}
/**
* @brief Read all key values in one scan cycle
*
* @param void
* @return none
*/
static void flex_button_read(void)
{
uint8_t i;
flex_button_t* target;
/* The button that was registered first, the button value is in the low position of raw_data */
btn_type_t raw_data = 0;
for(target = btn_head, i = button_cnt - 1;
(target != NULL) && (target->usr_button_read != NULL);
target = target->next, i--)
{
raw_data = raw_data | ((target->usr_button_read)(target) << i);
}
g_btn_status_reg = (~raw_data) ^ g_logic_level;
}
/**
* @brief Handle all key events in one scan cycle.
* Must be used after 'flex_button_read' API
*
* @param void
* @return Activated button count
*/
static uint8_t flex_button_process(void)
{
uint8_t i;
uint8_t active_btn_cnt = 0;
flex_button_t* target;
for (target = btn_head, i = button_cnt - 1; target != NULL; target = target->next, i--)
{
if (target->status > FLEX_BTN_STAGE_DEFAULT)
{
target->scan_cnt ++;
if (target->scan_cnt >= ((1 << (sizeof(target->scan_cnt) * 8)) - 1))
{
target->scan_cnt = target->long_hold_start_tick;
}
}
switch (target->status)
{
case FLEX_BTN_STAGE_DEFAULT: /* stage: default(button up) */
if (BTN_IS_PRESSED(i)) /* is pressed */
{
target->scan_cnt = 0;
target->click_cnt = 0;
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_DOWN);
/* swtich to button down stage */
target->status = FLEX_BTN_STAGE_DOWN;
}
else
{
target->event = FLEX_BTN_PRESS_NONE;
}
break;
case FLEX_BTN_STAGE_DOWN: /* stage: button down */
if (BTN_IS_PRESSED(i)) /* is pressed */
{
if (target->click_cnt > 0) /* multiple click */
{
if (target->scan_cnt > target->max_multiple_clicks_interval)
{
EVENT_SET_AND_EXEC_CB(target,
target->click_cnt < FLEX_BTN_PRESS_REPEAT_CLICK ?
target->click_cnt :
FLEX_BTN_PRESS_REPEAT_CLICK);
/* swtich to button down stage */
target->status = FLEX_BTN_STAGE_DOWN;
target->scan_cnt = 0;
target->click_cnt = 0;
}
}
else if (target->scan_cnt >= target->long_hold_start_tick)
{
if (target->event != FLEX_BTN_PRESS_LONG_HOLD)
{
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_LONG_HOLD);
}
}
else if (target->scan_cnt >= target->long_press_start_tick)
{
if (target->event != FLEX_BTN_PRESS_LONG_START)
{
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_LONG_START);
}
}
else if (target->scan_cnt >= target->short_press_start_tick)
{
if (target->event != FLEX_BTN_PRESS_SHORT_START)
{
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_SHORT_START);
}
}
}
else /* button up */
{
if (target->scan_cnt >= target->long_hold_start_tick)
{
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_LONG_HOLD_UP);
target->status = FLEX_BTN_STAGE_DEFAULT;
}
else if (target->scan_cnt >= target->long_press_start_tick)
{
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_LONG_UP);
target->status = FLEX_BTN_STAGE_DEFAULT;
}
else if (target->scan_cnt >= target->short_press_start_tick)
{
EVENT_SET_AND_EXEC_CB(target, FLEX_BTN_PRESS_SHORT_UP);
target->status = FLEX_BTN_STAGE_DEFAULT;
}
else
{
/* swtich to multiple click stage */
target->status = FLEX_BTN_STAGE_MULTIPLE_CLICK;
target->click_cnt ++;
}
}
break;
case FLEX_BTN_STAGE_MULTIPLE_CLICK: /* stage: multiple click */
if (BTN_IS_PRESSED(i)) /* is pressed */
{
/* swtich to button down stage */
target->status = FLEX_BTN_STAGE_DOWN;
target->scan_cnt = 0;
}
else
{
if (target->scan_cnt > target->max_multiple_clicks_interval)
{
EVENT_SET_AND_EXEC_CB(target,
target->click_cnt < FLEX_BTN_PRESS_REPEAT_CLICK ?
target->click_cnt :
FLEX_BTN_PRESS_REPEAT_CLICK);
/* swtich to default stage */
target->status = FLEX_BTN_STAGE_DEFAULT;
}
}
break;
}
if (target->status > FLEX_BTN_STAGE_DEFAULT)
{
active_btn_cnt ++;
}
}
return active_btn_cnt;
}
/**
* flex_button_event_read
*
* @brief Get the button event of the specified button.
*
* @param button: button structure instance
* @return button event
*/
flex_button_event_t flex_button_event_read(flex_button_t* button)
{
return (flex_button_event_t)(button->event);
}
/**
* flex_button_scan
*
* @brief Start key scan.
* Need to be called cyclically within the specified period.
* Sample cycle: 5 - 20ms
*
* @param void
* @return Activated button count
*/
uint8_t flex_button_scan(void)
{
flex_button_read();
return flex_button_process();
}

View File

@@ -0,0 +1,155 @@
/**
* @File: flexible_button.h
* @Author: MurphyZhao
* @Date: 2018-09-29
*
* Copyright (c) 2018-2019 MurphyZhao <d2014zjt@163.com>
* https://github.com/murphyzhao
* All rights reserved.
* License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Change logs:
* Date Author Notes
* 2018-09-29 MurphyZhao First add
* 2019-08-02 MurphyZhao Migrate code to github.com/murphyzhao account
* 2019-12-26 MurphyZhao Refactor code and implement multiple clicks
*
*/
#ifndef __FLEXIBLE_BUTTON_H__
#define __FLEXIBLE_BUTTON_H__
#include "stdint.h"
#define FLEX_BTN_SCAN_FREQ_HZ CONFIG_BUTTON_THREAD_SCAN_FREQ_HZ // How often flex_button_scan () is called
#define FLEX_MS_TO_SCAN_CNT(ms) (ms / (1000 / FLEX_BTN_SCAN_FREQ_HZ))
/* Multiple clicks interval, default 300ms */
#define MAX_MULTIPLE_CLICKS_INTERVAL (FLEX_MS_TO_SCAN_CNT(300))
typedef void (*flex_button_response_callback)(void*);
typedef enum
{
FLEX_BTN_PRESS_DOWN = 0,
FLEX_BTN_PRESS_CLICK,
FLEX_BTN_PRESS_DOUBLE_CLICK,
FLEX_BTN_PRESS_REPEAT_CLICK,
FLEX_BTN_PRESS_SHORT_START,
FLEX_BTN_PRESS_SHORT_UP,
FLEX_BTN_PRESS_LONG_START,
FLEX_BTN_PRESS_LONG_UP,
FLEX_BTN_PRESS_LONG_HOLD,
FLEX_BTN_PRESS_LONG_HOLD_UP,
FLEX_BTN_PRESS_MAX,
FLEX_BTN_PRESS_NONE,
} flex_button_event_t;
/**
* flex_button_t
*
* @brief Button data structure
* Below are members that need to user init before scan.
*
* @member next
* Internal use.
* One-way linked list, pointing to the next button.
*
* @member usr_button_read
* User function is used to read button vaule.
*
* @member cb
* Button event callback function.
*
* @member scan_cnt
* Internal use, user read-only.
* Number of scans, counted when the button is pressed, plus one per scan cycle.
*
* @member click_cnt
* Internal use, user read-only.
* Number of button clicks
*
* @member max_multiple_clicks_interval
* Multiple click interval. Default 'MAX_MULTIPLE_CLICKS_INTERVAL'.
* Need to use FLEX_MS_TO_SCAN_CNT to convert milliseconds into scan cnts.
*
* @member debounce_tick
* Debounce. Not used yet.
* Need to use FLEX_MS_TO_SCAN_CNT to convert milliseconds into scan cnts.
*
* @member short_press_start_tick
* Short press start time. Requires user configuration.
* Need to use FLEX_MS_TO_SCAN_CNT to convert milliseconds into scan cnts.
*
* @member long_press_start_tick
* Long press start time. Requires user configuration.
* Need to use FLEX_MS_TO_SCAN_CNT to convert milliseconds into scan cnts.
*
* @member long_hold_start_tick
* Long hold press start time. Requires user configuration.
*
* @member id
* Button id. Requires user configuration.
* When multiple buttons use the same button callback function,
* they are used to distinguish the buttons.
* Each button id must be unique.
*
* @member pressed_logic_level
* Requires user configuration.
* The logic level of the button pressed, each bit represents a button.
*
* @member event
* Internal use, users can call 'flex_button_event_read' to get current button event.
* Used to record the current button event.
*
* @member status
* Internal use, user unavailable.
* Used to record the current state of buttons.
*
*/
typedef struct flex_button
{
struct flex_button* next;
uint8_t (*usr_button_read)(void *);
flex_button_response_callback cb;
uint16_t scan_cnt;
uint16_t click_cnt;
uint16_t max_multiple_clicks_interval;
uint16_t debounce_tick;
uint16_t short_press_start_tick;
uint16_t long_press_start_tick;
uint16_t long_hold_start_tick;
uint8_t id;
uint8_t pressed_logic_level : 1;
uint8_t event : 4;
uint8_t status : 3;
} flex_button_t;
#ifdef __cplusplus
extern "C" {
#endif
int32_t flex_button_register(flex_button_t *button);
flex_button_event_t flex_button_event_read(flex_button_t* button);
uint8_t flex_button_scan(void);
#ifdef __cplusplus
}
#endif
#endif /* __FLEXIBLE_BUTTON_H__ */

View File

@@ -0,0 +1,47 @@
config BUTTON
bool "include gpio button and adc button"
default n
if BUTTON
config BUTTON_THREAD_SCAN_FREQ_HZ
int "button thread scan freq hz"
default 50
config BUTTON_THREAD_PRIORITY
int "button thread priority"
default 8
config BUTTON_THREAD_STACK_SIZE
int "button thread stack size"
default 4096
config GPIO_BUTTON
bool "gpio button"
default n
config ADC_BUTTON
bool "adc button"
default n
if ADC_BUTTON
config ADC_UNIT_NUM
int "adc uint number"
default 1
config ADC_MAX_CHANNEL
int "adc max channel"
default 6
range 1 6
config ADC_BUTTON_MAX_BUTTON_PER_CHANNEL
int "adc button max button per channel"
default 10
range 1 10
config ADC_BUTTON_SAMPLE_TIMES
int "adc button sample times"
default 8
endif
endif

View File

@@ -0,0 +1,57 @@
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include "lisa_log.h"
#include "lisa_thread.h"
#include "lisa_mutex.h"
#include "flexible_button.h"
#define TAG "btn"
static lisa_mutex_t *btn_mutex = NULL;
static void lisa_btn_task(void *arg)
{
LISA_LOGI(TAG, "lisa_btn_task enter");
// lisa_thread_mdelay(2000);
while (1) {
lisa_mutex_lock(btn_mutex, LISA_OS_WAIT_FOREVER);
flex_button_scan();
lisa_mutex_unlock(btn_mutex);
lisa_thread_mdelay(1000 / FLEX_BTN_SCAN_FREQ_HZ);
}
}
void button_create(flex_button_t *btn)
{
static bool is_init = false;
if (!btn_mutex) {
btn_mutex = lisa_mutex_create();
if (btn_mutex == NULL) {
LISA_LOGE(TAG, "btn_mutex lisa_mutex_create failed");
}
LISA_ASSERT(btn_mutex, "lisa btn mutex create failed");
}
lisa_mutex_lock(btn_mutex, LISA_OS_WAIT_FOREVER);
flex_button_register(btn);
lisa_mutex_unlock(btn_mutex);
if (!is_init) {
lisa_thread_attr_t attr = {
.name = "btn",
.stack_size = CONFIG_BUTTON_THREAD_STACK_SIZE,
.priority = CONFIG_BUTTON_THREAD_PRIORITY,
};
lisa_thread_t *td = lisa_thread_create(&attr, lisa_btn_task, NULL);
LISA_ASSERT(td, "lisa btn task create failed");
is_init = true;
LISA_LOGI(TAG, "lisa btn init done");
}
}

View File

@@ -0,0 +1,52 @@
#pragma once
// #include <stddef.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
// #define __containerof(ptr, type, member) \
// ((type *)((char *)(ptr) - offsetof(type, member)))
#define LISA_RETURN_ON_FALSE(cond, ret) \
do { \
if (!(cond)) { \
printf("[%s] %d: %d\n", __FILE__, __LINE__, ret); \
return ret; \
} \
} while (0)
#define LISA_GOTO_ON_FALSE(cond, err) \
do { \
if (!(cond)) { \
printf("[%s] %d\n", __FILE__, __LINE__); \
goto err; \
} \
} while (0)
#define ENUM_TO_STR(e) (#e)
typedef struct {
uint32_t short_press_time_ms;
uint32_t long_press_time_ms;
uint32_t long_hold_time_ms;
uint32_t press_logic_level;
} button_config_t;
typedef enum {
LISA_BTN_PRESS_DOWN = 0,
LISA_BTN_PRESS_CLICK,
LISA_BTN_PRESS_DOUBLE_CLICK,
LISA_BTN_PRESS_REPEAT_CLICK,
LISA_BTN_PRESS_SHORT_START,
LISA_BTN_PRESS_SHORT_UP,
LISA_BTN_PRESS_LONG_START,
LISA_BTN_PRESS_LONG_UP,
LISA_BTN_PRESS_LONG_HOLD,
LISA_BTN_PRESS_LONG_HOLD_UP,
LISA_BTN_PRESS_MAX,
LISA_BTN_PRESS_NONE,
} button_event_t;
typedef void (*button_cb_t)(button_event_t evt, void *user);

View File

@@ -0,0 +1,260 @@
#if CONFIG_ADC_BUTTON
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include "lisa_log.h"
#include "Driver_GPIO.h"
#include "IOMuxManager.h"
#include "Driver_GPADC.h"
#include "adc_sample.h"
#include "PowerManager.h"
#include "ClockManager.h"
#include "flexible_button.h"
#include "button_adc.h"
#define TAG "adc_btn"
#define ADC_UNIT_NUM CONFIG_ADC_UNIT_NUM
#define ADC_BUTTON_MAX_CHANNEL CONFIG_ADC_MAX_CHANNEL
#define ADC_BUTTON_MAX_BUTTON CONFIG_ADC_BUTTON_MAX_BUTTON_PER_CHANNEL
#define NO_OF_SAMPLES CONFIG_ADC_BUTTON_SAMPLE_TIMES //Multisampling
typedef struct {
uint16_t min;
uint16_t max;
} button_data_t;
typedef struct {
uint8_t channel;
uint8_t is_init;
button_data_t btns[ADC_BUTTON_MAX_BUTTON];
} btn_adc_channel_t;
typedef struct {
uint32_t is_configured;
btn_adc_channel_t ch[ADC_BUTTON_MAX_CHANNEL];
uint8_t ch_num;
} btn_adc_unit_t;
typedef struct {
btn_adc_unit_t unit[ADC_UNIT_NUM];
} button_adc_t;
typedef struct {
flex_button_t base;
button_adc_cb_t cb;
button_adc_config_t cfg;
} button_adc_obj;
static button_adc_t g_button = {0};
static int find_unused_channel(adc_unit_t unit_id)
{
for (size_t i = 0; i < ADC_BUTTON_MAX_CHANNEL; i++) {
if (0 == g_button.unit[unit_id].ch[i].is_init) {
return i;
}
}
return -1;
}
static int find_channel(adc_unit_t unit_id, uint8_t channel)
{
for (size_t i = 0; i < ADC_BUTTON_MAX_CHANNEL; i++) {
if (channel == g_button.unit[unit_id].ch[i].channel) {
return i;
}
}
return -1;
}
static uint32_t get_adc_channel(uint8_t channel)
{
switch (channel) {
case 0:
return CSK_GPADC_CHANNEL_SEL_0;
case 1:
return CSK_GPADC_CHANNEL_SEL_1;
case 2:
return CSK_GPADC_CHANNEL_SEL_2;
case 3:
return CSK_GPADC_CHANNEL_SEL_3;
case 4:
return CSK_GPADC_CHANNEL_SEL_4;
case 5:
return CSK_GPADC_CHANNEL_SEL_5;
default:
LISA_LOGW(TAG, "channel:%d is not supported", channel);
return CSK_GPADC_CHANNEL_SEL_0;
break;
}
}
static uint32_t get_adc_voltage(adc_unit_t unit_id, uint8_t channel)
{
uint32_t adc_reading = 0;
int adc_raw = 0;
for (int i = 0; i < NO_OF_SAMPLES; i++) {
// adc_oneshot_read(g_button.unit[unit_id].adc_handle, channel, &adc_raw);
adc_raw = adc_sample_get_channel_value(0);
adc_reading += adc_raw;
}
adc_reading /= NO_OF_SAMPLES;
return adc_reading;
}
uint8_t button_adc_get_key_level(void *button_driver)
{
flex_button_t *btn = (flex_button_t *)button_driver;
button_adc_obj *adc_btn = __containerof(btn, button_adc_obj, base);
static uint16_t vol = 0;
uint32_t ch = adc_btn->cfg.adc_channel;
uint32_t index = adc_btn->cfg.button_index;
LISA_RETURN_ON_FALSE(ch < ADC_BUTTON_MAX_CHANNEL, 0);
LISA_RETURN_ON_FALSE(index < ADC_BUTTON_MAX_BUTTON, 0);
int ch_index = find_channel(adc_btn->cfg.unit_id, ch);
LISA_RETURN_ON_FALSE(ch_index >= 0, 0);
/** It starts only when the elapsed time is more than 1ms */
// if ((esp_timer_get_time() - g_button.unit[adc_btn->unit_id].ch[ch_index].last_time) > 1000) {
// vol = get_adc_voltage(adc_btn->unit_id, ch);
// g_button.unit[adc_btn->unit_id].ch[ch_index].last_time = esp_timer_get_time();
// }
vol = get_adc_voltage(adc_btn->cfg.unit_id, ch);
// g_button.unit[adc_btn->unit_id].ch[ch_index].last_time = esp_timer_get_time();
// g_button.unit[adc_btn->cfg.unit_id].ch[ch_index].last_time = 0;
if (vol <= g_button.unit[adc_btn->cfg.unit_id].ch[ch_index].btns[index].max &&
vol >= g_button.unit[adc_btn->cfg.unit_id].ch[ch_index].btns[index].min) {
return true;
}
return false;
}
static int adc_channel_io_init(adc_unit_t unit_id, uint8_t channel)
{
LISA_RETURN_ON_FALSE(unit_id < ADC_UNIT_NUM, false);
LISA_RETURN_ON_FALSE(channel < ADC_BUTTON_MAX_CHANNEL, false);
AON_IOMuxManager_PinConfigure(CSK_IOMUX_PAD_B, channel + 2, CSK_AON_IOMUX_FUNC_ALTER3);
switch (channel) {
case 0:
IP_AON_IOMUX->REG_PAD_AON_GPIOB_02.bit.PAD_AON_GPIOB_02_ANA_SEL = CSK_ANA_IOMUX_FUNC_DEFAULT;
break;
case 1:
IP_AON_IOMUX->REG_PAD_AON_GPIOB_03.bit.PAD_AON_GPIOB_03_ANA_SEL = CSK_ANA_IOMUX_FUNC_DEFAULT;
break;
case 2:
IP_AON_IOMUX->REG_PAD_AON_GPIOB_04.bit.PAD_AON_GPIOB_04_ANA_SEL = CSK_ANA_IOMUX_FUNC_DEFAULT;
break;
case 3:
IP_AON_IOMUX->REG_PAD_AON_GPIOB_05.bit.PAD_AON_GPIOB_05_ANA_SEL = CSK_ANA_IOMUX_FUNC_DEFAULT;
break;
case 4:
IP_AON_IOMUX->REG_PAD_AON_GPIOB_06.bit.PAD_AON_GPIOB_06_ANA_SEL = CSK_ANA_IOMUX_FUNC_DEFAULT;
break;
case 5:
IP_AON_IOMUX->REG_PAD_AON_GPIOB_07.bit.PAD_AON_GPIOB_07_ANA_SEL = CSK_ANA_IOMUX_FUNC_DEFAULT;
break;
default:
break;
}
}
static void button_adc_evt_cb(void *arg)
{
flex_button_t *btn = (flex_button_t *)arg;
button_adc_obj *adc_btn = __containerof(btn, button_adc_obj, base);
// LISA_LOGI(TAG, "btn id:%d, event_id:%d", btn->id, btn->event);
if (adc_btn->cb) {
adc_btn->cb((button_event_t)(btn->event), &adc_btn->cfg);
}
}
bool button_new_adc_device(button_config_t *button_config, button_adc_config_t *adc_config, button_adc_cb_t cb)
{
/* check */
LISA_RETURN_ON_FALSE((button_config && adc_config && cb), false);
LISA_RETURN_ON_FALSE(adc_config->unit_id < ADC_UNIT_NUM, false);
LISA_RETURN_ON_FALSE(adc_config->adc_channel < ADC_BUTTON_MAX_CHANNEL, false);
LISA_RETURN_ON_FALSE(adc_config->button_index < ADC_BUTTON_MAX_BUTTON, false);
LISA_RETURN_ON_FALSE(adc_config->min < adc_config->max, false);
LISA_RETURN_ON_FALSE(button_config->short_press_time_ms > 0, false);
LISA_RETURN_ON_FALSE(button_config->long_press_time_ms > 0, false);
LISA_RETURN_ON_FALSE(button_config->long_hold_time_ms > 0, false);
LISA_RETURN_ON_FALSE(button_config->long_press_time_ms > button_config->short_press_time_ms, false);
LISA_RETURN_ON_FALSE(button_config->long_hold_time_ms > button_config->long_press_time_ms, false);
LISA_RETURN_ON_FALSE(button_config->press_logic_level < 2, false);
button_adc_obj *adc_btn = calloc(1, sizeof(button_adc_obj));
LISA_RETURN_ON_FALSE(adc_btn, false);
/* find channel */
int ch_index = find_channel(adc_config->unit_id, adc_config->adc_channel);
if (ch_index >= 0) { /**< the channel has been initialized */
LISA_GOTO_ON_FALSE(g_button.unit[adc_config->unit_id].ch[ch_index].btns[adc_config->button_index].max == 0, err);
} else { /**< this is a new channel */
int unused_ch_index = find_unused_channel(adc_config->unit_id);
LISA_GOTO_ON_FALSE(unused_ch_index >= 0, err);
ch_index = unused_ch_index;
}
/* adc init */
if (0 == g_button.unit[adc_config->unit_id].is_configured) {
// if (NULL == adc_config->adc_handle) {
// adc init
adc_sample_init();
// LISA_GOTO_ON_FALSE(adc_config->adc_handle, err);
g_button.unit[adc_config->unit_id].is_configured = 1;
// } else {
// g_button.unit[adc_config->unit_id].adc_handle = *adc_config->adc_handle;
// LOGI(TAG, "ADC1 has been initialized");
// g_button.unit[adc_config->unit_id].is_configured = 1;
// }
}
/* adc channel io init */
if (0 == g_button.unit[adc_config->unit_id].ch[ch_index].is_init) {
// adc_channel_io_init(adc_config->unit_id, adc_config->adc_channel);
g_button.unit[adc_config->unit_id].ch[ch_index].channel = adc_config->adc_channel;
g_button.unit[adc_config->unit_id].ch[ch_index].is_init = 1;
// g_button.unit[adc_config->unit_id].ch[ch_index].last_time = 0;
}
g_button.unit[adc_config->unit_id].ch[ch_index].btns[adc_config->button_index].max = adc_config->max;
g_button.unit[adc_config->unit_id].ch[ch_index].btns[adc_config->button_index].min = adc_config->min;
g_button.unit[adc_config->unit_id].ch_num++;
adc_btn->cb = cb;
memcpy(&adc_btn->cfg, adc_config, sizeof(button_adc_config_t));
/* register to flex_button */
adc_btn->base.usr_button_read = button_adc_get_key_level;
adc_btn->base.cb = button_adc_evt_cb;
adc_btn->base.pressed_logic_level = 1;
adc_btn->base.short_press_start_tick = FLEX_MS_TO_SCAN_CNT(button_config->short_press_time_ms);
adc_btn->base.long_press_start_tick = FLEX_MS_TO_SCAN_CNT(button_config->long_press_time_ms);
adc_btn->base.long_hold_start_tick = FLEX_MS_TO_SCAN_CNT(button_config->long_hold_time_ms);
button_create(&adc_btn->base);
// *handle = adc_btn;
return true;
err:
if (adc_btn) {
free(adc_btn);
}
return false;
}
#endif /* CONFIG_ADC_BUTTON */

View File

@@ -0,0 +1,22 @@
#pragma once
#if CONFIG_ADC_BUTTON
#include "button.h"
typedef uint32_t adc_unit_t;
typedef struct {
void *adc_handle; /**< handle of adc unit, if NULL will create new one internal, else will use the handle */
adc_unit_t unit_id; /**< ADC unit */
uint8_t adc_channel; /**< Channel of ADC */
uint8_t button_index; /**< button index on the channel */
uint16_t min; /**< min voltage in mv corresponding to the button */
uint16_t max; /**< max voltage in mv corresponding to the button */
} button_adc_config_t;
typedef void (*button_adc_cb_t)(button_event_t evt, button_adc_config_t *user_data);
bool button_new_adc_device(button_config_t *button_config, button_adc_config_t *adc_config, button_adc_cb_t cb);
#endif /* CONFIG_ADC_BUTTON */

View File

@@ -0,0 +1,118 @@
#if CONFIG_GPIO_BUTTON
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#include "lisa_log.h"
#include "Driver_GPIO.h"
#include "IOMuxManager.h"
#include "flexible_button.h"
#include "button_gpio.h"
#define TAG "gpio_btn"
#define GPIO_PORT_NUM 2
typedef struct {
button_gpio_cb_t cb; /**< button callback */
button_gpio_config_t cfg; /**< button config */
flex_button_t base; /**< button driver */
} button_gpio_obj;
static bool gpio_is_valid(uint8_t gpio_port, uint8_t gpio_pin_num);
uint8_t button_gpio_get_key_level(void *button_driver)
{
flex_button_t *btn = (flex_button_t *)button_driver;
uint8_t gpio_level = 0;
button_gpio_obj *gpio_btn = __containerof(btn, button_gpio_obj, base);
LISA_RETURN_ON_FALSE(gpio_btn->cfg.gpio_port < GPIO_PORT_NUM, false);
LISA_RETURN_ON_FALSE(gpio_is_valid(gpio_btn->cfg.gpio_port, gpio_btn->cfg.gpio_pin_num), false);
if (gpio_btn->cfg.gpio_port == CSK_IOMUX_PAD_A){
gpio_level = GPIO_PinRead(GPIOA(), (1UL << gpio_btn->cfg.gpio_pin_num));
} else {
gpio_level = GPIO_PinRead(GPIOB(), (1UL << gpio_btn->cfg.gpio_pin_num));
}
return gpio_level;
}
static void button_gpio_evt_cb(void *arg)
{
flex_button_t *btn = (flex_button_t *)arg;
button_gpio_obj *gpio_btn = __containerof(btn, button_gpio_obj, base);
// LISA_LOGI(TAG, "gpio btn id:%d, event_id:%d", btn->id, btn->event);
if (gpio_btn->cb) {
gpio_btn->cb((button_event_t)(btn->event), &gpio_btn->cfg);
}
}
static bool gpio_is_valid(uint8_t gpio_port, uint8_t gpio_pin_num)
{
if (gpio_port == CSK_IOMUX_PAD_A) {
return (gpio_pin_num < CSK_IOMUX_PAD_A_MAX_PIN);
} else if (gpio_port == CSK_IOMUX_PAD_B) {
return (gpio_pin_num < CSK_IOMUX_PAD_B_MAX_PIN);
} else {
return false;
}
}
static void button_gpio_init(uint8_t gpio_port, uint8_t gpio_pin_num)
{
IOMuxManager_PinConfigure(gpio_port, gpio_pin_num, CSK_IOMUX_FUNC_DEFAULT);
if (gpio_port == CSK_IOMUX_PAD_A){
GPIO_SetDir(GPIOA(), (1UL << gpio_pin_num), CSK_GPIO_DIR_INPUT);
} else {
GPIO_SetDir(GPIOB(), (1UL << gpio_pin_num), CSK_GPIO_DIR_INPUT);
}
}
bool button_new_gpio_device(button_config_t *button_config, button_gpio_config_t *gpio_config, button_gpio_cb_t cb)
{
/* check */
LISA_RETURN_ON_FALSE((button_config && gpio_config && cb), false);
LISA_RETURN_ON_FALSE(gpio_config->gpio_port < GPIO_PORT_NUM, false);
LISA_RETURN_ON_FALSE(gpio_is_valid(gpio_config->gpio_port, gpio_config->gpio_pin_num), false);
LISA_RETURN_ON_FALSE(button_config->short_press_time_ms > 0, false);
LISA_RETURN_ON_FALSE(button_config->long_press_time_ms > 0, false);
LISA_RETURN_ON_FALSE(button_config->long_hold_time_ms > 0, false);
LISA_RETURN_ON_FALSE(button_config->long_press_time_ms > button_config->short_press_time_ms, false);
LISA_RETURN_ON_FALSE(button_config->long_hold_time_ms > button_config->long_press_time_ms, false);
LISA_RETURN_ON_FALSE(button_config->press_logic_level < 2, false);
button_gpio_obj *gpio_btn = calloc(1, sizeof(button_gpio_obj));
LISA_RETURN_ON_FALSE(gpio_btn, false);
/* gpio init */
button_gpio_init(gpio_config->gpio_port, gpio_config->gpio_pin_num);
gpio_btn->cb = cb;
memcpy(&gpio_btn->cfg, gpio_config, sizeof(button_gpio_config_t));
gpio_btn->base.usr_button_read = button_gpio_get_key_level;
gpio_btn->base.cb = button_gpio_evt_cb;
gpio_btn->base.pressed_logic_level = button_config->press_logic_level;
gpio_btn->base.short_press_start_tick = FLEX_MS_TO_SCAN_CNT(button_config->short_press_time_ms);
gpio_btn->base.long_press_start_tick = FLEX_MS_TO_SCAN_CNT(button_config->long_press_time_ms);
gpio_btn->base.long_hold_start_tick = FLEX_MS_TO_SCAN_CNT(button_config->long_hold_time_ms);
button_create(&gpio_btn->base);
return true;
err:
if (gpio_btn) {
free(gpio_btn);
}
return false;
}
#endif /* CONFIG_GPIO_BUTTON */

View File

@@ -0,0 +1,17 @@
#pragma once
#if CONFIG_GPIO_BUTTON
#include "button.h"
typedef struct {
// button_handle_t *button_handle;
uint32_t gpio_port;
uint32_t gpio_pin_num;
} button_gpio_config_t;
typedef void (*button_gpio_cb_t)(button_event_t evt, button_gpio_config_t *user_data);
bool button_new_gpio_device(button_config_t *button_config, button_gpio_config_t *gpio_config, button_gpio_cb_t cb);
#endif /* CONFIG_GPIO_BUTTON */

View File

@@ -0,0 +1,45 @@
#include "button_adc.h"
static void adc_button_callback(button_event_t evt, button_adc_config_t *user_data)
{
printf("adc_button_index: %d, event: %d\n", user_data->button_index, evt);
}
void test_adc_button(void)
{
button_adc_config_t btn_adc_cfg = {
.unit_id = 0,
.adc_channel = 0, // PB2
};
button_config_t btn_cfg = {
.short_press_time_ms = 1500,
.long_press_time_ms = 2000,
.long_hold_time_ms = 4500,
.press_logic_level = 1,
};
const uint16_t vol[10] = {369, 474, 602, 752, 913, 1051, 1203, 1340, 1494, 1641};
for (int i = 0; i < CONFIG_ADC_BUTTON_MAX_BUTTON_PER_CHANNEL; i++) {
btn_adc_cfg.button_index = i;
if (i == 0) {
btn_adc_cfg.min = (0 + vol[i]) / 2;
} else {
btn_adc_cfg.min = (vol[i - 1] + vol[i]) / 2;
}
if (i == 9) {
btn_adc_cfg.max = (vol[i] + 3000) / 2;
} else {
btn_adc_cfg.max = (vol[i] + vol[i + 1]) / 2;
}
button_new_adc_device(&btn_cfg, &btn_adc_cfg, adc_button_callback);
}
// while (1) {
// lisa_thread_mdelay(1000);
// }
}

View File

@@ -0,0 +1,35 @@
#include "button_gpio.h"
#include "IOMuxManager.h"
static void gpio_button_callback(button_event_t evt, button_gpio_config_t *user_data)
{
printf("gpio_button_port: %d, pin:%d, event: %d\n", user_data->gpio_port, user_data->gpio_pin_num, evt);
}
void test_gpio_button(void)
{
button_config_t btn_cfg = {
.short_press_time_ms = 1500,
.long_press_time_ms = 2000,
.long_hold_time_ms = 4500,
.press_logic_level = 0,
};
button_gpio_config_t btn_gpio_cfg = {0};
btn_gpio_cfg.gpio_port = CSK_IOMUX_PAD_A;
btn_gpio_cfg.gpio_pin_num = 12;
button_new_gpio_device(&btn_cfg, &btn_gpio_cfg, gpio_button_callback);
btn_gpio_cfg.gpio_port = CSK_IOMUX_PAD_A;
btn_gpio_cfg.gpio_pin_num = 16;
button_new_gpio_device(&btn_cfg, &btn_gpio_cfg, gpio_button_callback);
btn_gpio_cfg.gpio_port = CSK_IOMUX_PAD_A;
btn_gpio_cfg.gpio_pin_num = 27;
button_new_gpio_device(&btn_cfg, &btn_gpio_cfg, gpio_button_callback);
// btn_gpio_cfg.gpio_port = CSK_IOMUX_PAD_A;
// btn_gpio_cfg.gpio_pin_num = 0;
// button_new_gpio_device(&btn_cfg, &btn_gpio_cfg, gpio_button_callback);
}

View File

@@ -0,0 +1,9 @@
listenai_library_named(video_camera)
listenai_library_sources(
video_camera.c
)
listenai_include_directories(
${CMAKE_CURRENT_SOURCE_DIR}
)

View File

@@ -0,0 +1,448 @@
/*
* Copyright (c) 2025, LISTENAI
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @file main.c
* @brief LISA Camera 摄像头驱动示例
*
* 演示内容:
* 1. 初始化摄像头设备并配置总线接口(DVP)
* 2. 配置摄像头参数(分辨率、像素格式等)
* 3. 捕获图像帧并通过串口发送
*
* 注意:本示例需要实际连接摄像头硬件才能正常运行
*/
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#include "lisa_device.h"
#include "lisa_camera.h"
#include "FreeRTOS.h"
#include "task.h"
#include "lisa_gpio.h"
#include "lisa_uart.h"
#include "IOMuxManager.h"
#include "video_camera.h"
#define TAG "video_camera"
#include <lisa_log.h>
/* 摄像头设备名称 */
#define CAMERA_DEVICE "camera"
/* DVP设备名称 */
#define DVP_DEVICE "dvp0"
/* DMA 通道 */
#define DMA_CHANNEL 2
/* Static variables */
static lisa_device_t *camera_dev = NULL;
static bool is_initialized = false;
static bool is_capturing = false;
/* Callback */
static camera_frame_callback_t frame_callback = NULL;
static void *callback_user_data = NULL;
/* ========================================================================
* DVP 引脚配置
* ======================================================================== */
#ifdef CONFIG_BOARD_ARCS_EVB
#define CAM_PWDN_PIN 7
#define CAM_HSYNC_PIN 10
#define CAM_VSYNC_PIN 11
#define CAM_PCLK_PIN 12
#define CAM_MCLK_PIN 26
#define CAM_D0_PIN 13
#define CAM_D1_PIN 14
#define CAM_D2_PIN 15
#define CAM_D3_PIN 16
#define CAM_D4_PIN 17
#define CAM_D5_PIN 18
#define CAM_D6_PIN 19
#define CAM_D7_PIN 20
// void lisa_gpiob_pinmux(void)
// {
// IOMuxManager_PinConfigure(CSK_IOMUX_PAD_B, CAM_PWDN_PIN, CSK_IOMUX_FUNC_DEFAULT);
// }
void lisa_uart1_pinmux()
{
// IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, 21, CSK_IOMUX_FUNC_ALTER3);
}
// void lisa_i2c0_pinmux(void)
// {
// IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, 22, 8);
// IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, 23, 8);
// }
void lisa_dvp_pinmux(void)
{
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, CAM_HSYNC_PIN, CSK_IOMUX_FUNC_ALTER16);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, CAM_VSYNC_PIN, CSK_IOMUX_FUNC_ALTER16);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, CAM_PCLK_PIN, CSK_IOMUX_FUNC_ALTER16);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, CAM_D0_PIN, CSK_IOMUX_FUNC_ALTER16);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, CAM_D1_PIN, CSK_IOMUX_FUNC_ALTER16);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, CAM_D2_PIN, CSK_IOMUX_FUNC_ALTER16);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, CAM_D3_PIN, CSK_IOMUX_FUNC_ALTER16);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, CAM_D4_PIN, CSK_IOMUX_FUNC_ALTER16);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, CAM_D5_PIN, CSK_IOMUX_FUNC_ALTER16);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, CAM_D6_PIN, CSK_IOMUX_FUNC_ALTER16);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, CAM_D7_PIN, CSK_IOMUX_FUNC_ALTER16);
}
#endif
static void video_camera_release_fb(void *data)
{
lisa_camera_fb_t *fb = (lisa_camera_fb_t *)data;
if (camera_dev) {
/* Release frame */
lisa_camera_release_fb(camera_dev, fb);
}
}
static void capture_task(void *arg)
{
(void)arg;
int ret = 0;
LOGI("Capture task started");
while (1) {
camera_frame_t frame;
lisa_camera_fb_t *fb = NULL;
if (!is_capturing) {
vTaskDelay(pdMS_TO_TICKS(10));
continue;
}
/* Get frame from camera */
ret = lisa_camera_capture(camera_dev, &fb);
if (ret != LISA_DEVICE_OK || fb == NULL) {
LOGE("Capture failed: %d", ret);
vTaskDelay(pdMS_TO_TICKS(100));
continue;
}
/* Fill frame structure */
frame.buffer = fb->buf;
frame.length = fb->len;
frame.width = fb->width;
frame.height = fb->height;
frame.format = fb->format;
frame.func = video_camera_release_fb;
frame.func_param = (void *)fb;
/* Call callback if registered */
if (frame_callback) {
frame_callback(&frame, callback_user_data);
}
}
LOGI("Capture task stopped");
}
int video_camera_init(camera_config_t *config)
{
int ret = 0;
LISA_LOGI(TAG, "camera config: w:%d, h:%d, format:%d", config->width, config->height, config->format);
if (is_initialized) {
LOGW("Camera already initialized");
return 0;
}
if(!config)
{
LOGE("camera config is NULL");
return -1;
}
/* Get camera device */
camera_dev = lisa_device_get(CAMERA_DEVICE);
if (!lisa_device_ready(camera_dev)) {
LOGE("Camera device not ready");
return -1;
}
LOGI("%s device ready", CAMERA_DEVICE);
/* Configure GPIO for camera power control */
lisa_device_t *gpioa = lisa_device_get("gpioa");
if (gpioa) {
lisa_gpio_configure(gpioa, 23, LISA_GPIO_CONFIG_OUTPUT_HIGH);
}
/* Get I2C device for camera configuration */
lisa_device_t *i2c_dev = lisa_device_get("i2c0");
if (!lisa_device_ready(i2c_dev)) {
LOGE("I2C device not ready");
return -1;
}
/* 配置摄像头参数 */
lisa_camera_config_t camera_config = {
.hw_config = {
.mclk_pad = CSK_IOMUX_PAD_A,
.mclk_pin = CAM_MCLK_PIN,
.pwdn_gpio_dev = lisa_device_get("gpiob"),
.pwdn_pin = CAM_PWDN_PIN,
.pwdn_delay_us = 0,
.xclk_delay_us = 0,
.i2c_dev = i2c_dev,
},
.xclk_freq_hz = 8000000,
.fb_count = 4,
.enable_hmirror = false,
.enable_vflip = false,
.enable_colorbar = false,
};
LOGI("Setting up camera...");
ret = lisa_camera_setup(camera_dev, &camera_config);
if (ret != LISA_DEVICE_OK) {
LOGE("Failed to setup camera: %d", ret);
return -1;
}
lisa_camera_capabilities_t caps;
ret = lisa_camera_get_capabilities(camera_dev, &caps);
if (ret != LISA_DEVICE_OK) {
LOGE("Failed to get capabilities: %d", ret);
return -1;
}
LOGI("Camera capabilities: max_width=%u, max_height=%u, supported_formats=0x%08X",
caps.max_width, caps.max_height, caps.supported_formats);
uint16_t x = 320 - (config->width / 2);
uint16_t y = 240 - (config->height / 2);
LISA_LOGI(TAG, "crop:x:%u, y:%u, w:%d, h:%d", x, y, config->width, config->height);
lisa_camera_crop_t crop = {
.x = x,
.y = y,
.width = config->width,
.height = config->height,
};
ret = lisa_camera_set_crop(camera_dev, &crop);
if (ret != LISA_DEVICE_OK) {
LOGE("Failed to set crop: %d", ret);
return -1;
}
ret = lisa_camera_set_pixformat(camera_dev, config->format);
if (ret != LISA_DEVICE_OK) {
LOGE("Failed to set pixformat: %d, ret:%d", config->format, ret);
return -1;
}
ret = lisa_camera_set_hmirror(camera_dev, true);
if (ret != LISA_DEVICE_OK) {
LOGE("Failed to set hmirror: %d, ret:%d", true, ret);
return -1;
}
video_camera_set_gray(true);
/* 配置 DVP 总线接口 */
lisa_camera_bus_config_t bus_config = {
.dma_channel = DMA_CHANNEL,
.bus_type = LISA_CAMERA_BUS_DVP,
.config.dvp = {
.dvp_dev = lisa_device_get("dvp0"),
.dvp_freq = 8000000,
.data_align = 1,
.line_offset = 0,
.pixel_offset = 0,
.pclk_polarity = 0,
.vsync_polarity = 1,
.hsync_polarity = 1,
}
};
lisa_camera_get_framesize(camera_dev, &bus_config.width, &bus_config.height);
bus_config.pixel_format = lisa_camera_get_pixformat(camera_dev);
ret = lisa_camera_attach_bus(camera_dev, &bus_config);
if (ret != LISA_DEVICE_OK) {
LOGE("Failed to attach bus: %d", ret);
return -1;
}
is_initialized = true;
/* Create capture task */
xTaskCreate(capture_task, "camera_task", 4096, NULL, configMAX_PRIORITIES - 1, NULL);
LOGI("Camera capture started with internal task");
return 0;
}
int video_camera_deinit(void)
{
if (!is_initialized) {
return 0;
}
if (is_capturing) {
video_camera_stop_capture();
}
if (camera_dev) {
lisa_camera_deinit(camera_dev);
}
is_initialized = false;
camera_dev = NULL;
LOGI("video_camera deinitialized");
return 0;
}
int video_camera_register_callback(camera_frame_callback_t callback, void *user_data)
{
if (!callback) {
LOGE("Invalid callback");
return -1;
}
frame_callback = callback;
callback_user_data = user_data;
LOGI("Frame callback registered");
return 0;
}
int video_camera_start_capture(void)
{
if (!is_initialized) {
return -1;
}
if (is_capturing) {
LOGW("Camera already capturing");
return 0;
}
/* Start camera hardware */
int ret = lisa_camera_start(camera_dev);
if (ret != 0) {
LOGE("Camera start failed: %d", ret);
return ret;
}
is_capturing = true;
return 0;
}
int video_camera_stop_capture(void)
{
if (!is_capturing) {
return 0;
}
is_capturing = false;
if (camera_dev) {
lisa_camera_stop(camera_dev);
}
LOGI("Camera capture stopped");
return 0;
}
static volatile bool is_set = false;
int video_camera_set_gray(bool enable)
{
int ret = 0;
if (enable) {
if (is_set == true) {
LOGE("camera_set_gray already on\r\n");
return -1;
}
video_camera_stop_capture();
ret = lisa_camera_set_reg(camera_dev, 0XFE, 0xff, 0x00); // select page 0
if (ret != LISA_DEVICE_OK) {
LOGE("%s, %d, Failed to set pixformat: GRAY ret:%d", __FUNCTION__, __LINE__, ret);
video_camera_start_capture();
return -1;
}
ret = lisa_camera_set_reg(camera_dev, 0x43, 0x02, 0x02); // CbCr fixed enable
if (ret != LISA_DEVICE_OK) {
LOGE("%s, %d, Failed to set pixformat: GRAY ret:%d", __FUNCTION__, __LINE__, ret);
video_camera_start_capture();
return -1;
}
ret = lisa_camera_set_reg(camera_dev, 0xda, 0xff, 0x00); // Cb fixed 0x00
if (ret != LISA_DEVICE_OK) {
LOGE("%s, %d, Failed to set pixformat: GRAY ret:%d", __FUNCTION__, __LINE__, ret);
video_camera_start_capture();
return -1;
}
ret = lisa_camera_set_reg(camera_dev, 0xdb, 0xff, 0x00); // Cr fixed 0x00
if (ret != LISA_DEVICE_OK) {
LOGE("%s, %d, Failed to set pixformat: GRAY ret:%d", __FUNCTION__, __LINE__, ret);
video_camera_start_capture();
return -1;
}
is_set = true;
video_camera_start_capture();
LOGI("camera_set_gray on success\r\n");
} else {
if (is_set == false) {
LOGE("camera_set_gray already off\r\n");
return -1;
}
video_camera_stop_capture();
ret = lisa_camera_set_reg(camera_dev, 0XFE, 0xff, 0x00); // select page 0
if (ret != LISA_DEVICE_OK) {
LOGE("%s, %d, Failed to set pixformat: YUV422 ret:%d", __FUNCTION__, __LINE__, ret);
video_camera_start_capture();
return -1;
}
ret = lisa_camera_set_reg(camera_dev, 0x43, 0x02, 0x00); // CbCr fixed disable
if (ret != LISA_DEVICE_OK) {
LOGE("%s, %d, Failed to set pixformat: YUV422 ret:%d", __FUNCTION__, __LINE__, ret);
video_camera_start_capture();
return -1;
}
is_set = false;
video_camera_start_capture();
LOGI("camera_set_gray off success\r\n");
}
return 0;
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (c) 2025, LISTENAI
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include "lisa_camera.h"
typedef struct {
uint16_t width; /* Image width */
uint16_t height; /* Image height */
lisa_camera_pixel_format_t format; /* Pixel format (RGB565, YUV422, etc.) */
} camera_config_t;
typedef void (*camera_frame_release_t)(void *data);
typedef struct {
uint8_t *buffer; /* Frame buffer pointer */
uint32_t length; /* Frame data length */
uint16_t width; /* Frame width */
uint16_t height; /* Frame height */
lisa_camera_pixel_format_t format; /* Pixel format */
camera_frame_release_t func; /* camera buffer release function */
void *func_param; /* release function parameters */
} camera_frame_t;
typedef void (*camera_frame_callback_t)(camera_frame_t *frame, void *user_data);
int video_camera_init(camera_config_t *config);
int video_camera_deinit(void);
int video_camera_start_capture(void);
int video_camera_stop_capture(void);
int video_camera_register_callback(camera_frame_callback_t callback, void *user_data);
int video_camera_set_gray(bool enable);

View File

@@ -0,0 +1,9 @@
listenai_library_named(display)
listenai_library_sources(
display.c
)
listenai_include_directories(
${CMAKE_CURRENT_SOURCE_DIR}
)

View File

@@ -0,0 +1,172 @@
/*
* Copyright (c) 2025, LISTENAI
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "lisa_device.h"
#include "lisa_display.h"
#include "lisa_touch.h"
#include "lv_demos.h"
#include "lv_port_indev.h"
#include "lv_port_disp.h"
#include "FreeRTOSConfig.h"
#include "IOMuxManager.h"
#include "board.h"
#define LOG_TAG "lvgl8_demo_widgets"
#include <lisa_log.h>
#define TOUCH_DEVICE "touch_cst328"
#define I2C_DEVICE "i2c0"
/*
为满足不同板型示例场景,重定向设备的pinmux配置
*/
#ifdef CONFIG_BOARD_ARCS_EVB
#define LCD_CS_PIN 5
#define LCD_SPI_CLK_PIN 3
#define LCD_SPI_DATA_PIN 1
/* Touch I2C 引脚定义 */
#define LISA_TOUCH_I2C_SDA_PORT CSK_IOMUX_PAD_A
#define LISA_TOUCH_I2C_SDA_PIN 22
#define LISA_TOUCH_I2C_SDA_FUNC 8
#define LISA_TOUCH_I2C_SCL_PORT CSK_IOMUX_PAD_A
#define LISA_TOUCH_I2C_SCL_PIN 23
#define LISA_TOUCH_I2C_SCL_FUNC 8
/* Touch GPIO 引脚定义 */
#define LISA_TOUCH_I2C_RST_PORT CSK_IOMUX_PAD_A
#define LISA_TOUCH_I2C_RST_PIN 25
#define LISA_TOUCH_I2C_RST_FUNC 0
#define LISA_TOUCH_I2C_INT_PORT CSK_IOMUX_PAD_A
#define LISA_TOUCH_I2C_INT_PIN 24
#define LISA_TOUCH_I2C_INT_FUNC 0
void lisa_gpioa_pinmux()
{
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, LCD_RST_PIN, CSK_IOMUX_FUNC_ALTER1);
IOMuxManager_PinConfigure(LISA_TOUCH_I2C_RST_PORT, LISA_TOUCH_I2C_RST_PIN, LISA_TOUCH_I2C_RST_FUNC);
IOMuxManager_PinConfigure(LISA_TOUCH_I2C_INT_PORT, LISA_TOUCH_I2C_INT_PIN, LISA_TOUCH_I2C_INT_FUNC);
}
void lisa_gpiob_pinmux()
{
#define CAM_PWDN_PIN 7
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_B, LCD_TE_PIN, CSK_IOMUX_FUNC_DEFAULT);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_B, LCD_CD_PIN, CSK_IOMUX_FUNC_DEFAULT);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_B, LCD_CS_PIN, CSK_IOMUX_FUNC_DEFAULT);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_B, CAM_PWDN_PIN, CSK_IOMUX_FUNC_DEFAULT);
}
void lisa_i2c0_pinmux()
{
IOMuxManager_PinConfigure(LISA_TOUCH_I2C_SDA_PORT, LISA_TOUCH_I2C_SDA_PIN, LISA_TOUCH_I2C_SDA_FUNC);
IOMuxManager_PinConfigure(LISA_TOUCH_I2C_SCL_PORT, LISA_TOUCH_I2C_SCL_PIN, LISA_TOUCH_I2C_SCL_FUNC);
}
void lisa_spi1_pinmux()
{
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_B, LCD_SPI_CLK_PIN, CSK_IOMUX_FUNC_ALTER6);
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_B, LCD_SPI_DATA_PIN, CSK_IOMUX_FUNC_ALTER6);
}
void lisa_pwm_pinmux()
{
IOMuxManager_PinConfigure(CSK_IOMUX_PAD_A, LCD_PWM_PIN, CSK_IOMUX_FUNC_ALTER12);
}
#endif
static void task_ui(void *pvParameters)
{
lv_obj_t *screen = screen_create();
lv_scr_load(screen); // 加载屏幕对象以显示
LOGI("LVGL screen loaded and started\r\n");
while (1) {
uint32_t wait_time = lv_task_handler();
// lisa_thread_mdelay(wait_time);
lisa_thread_mdelay(10);
}
}
int display_init(void)
{
lv_init();
lisa_device_t *gpioa_dev = lisa_device_get("gpioa");
lisa_device_t *gpiob_dev = lisa_device_get("gpiob");
lisa_display_config_t display_config = {
.bus_type = LISA_DISPLAY_BUS_SPI_4WIRE,
.bus_config = {.spi_4wire =
{
.spi_dev = lisa_device_get("spi1"),
.cs_gpio = gpiob_dev,
.cs_pin = LCD_CS_PIN,
.dc_gpio = gpiob_dev,
.dc_pin = LCD_CD_PIN,
.spi_freq = 50 * 1000 * 1000,
}},
.backlight = {.type = LISA_DISPLAY_BACKLIGHT_TYPE_PWM, .blacklight_polarity = LISA_DISPLAY_BLACKLIGHT_POLARITY_LOW,
.config.pwm = {.channel = 0, .dev = lisa_device_get("pwm0"), .freq = 2000}},
.rst_gpio = gpioa_dev,
.rst_pin = LCD_RST_PIN,
};
lisa_device_t *display_device = lisa_device_get("display");
if (!display_device) {
LISA_LOGE(LOG_TAG, "Failed to get display device");
return -1;
}
lisa_display_attach_bus(display_device, &display_config);
lv_port_disp_init(display_device);
lisa_display_blanking_off(display_device);
lisa_device_t *touch_dev = lisa_device_get(TOUCH_DEVICE);
if (!lisa_device_ready(touch_dev)) {
printf("Error: %s device not ready\n", TOUCH_DEVICE);
return -1;
}
// /* 获取I2C设备 */
// lisa_device_t *i2c_dev = lisa_device_get(I2C_DEVICE);
// if (!lisa_device_ready(i2c_dev)) {
// printf("Error: %s device not ready\n", I2C_DEVICE);
// return -1;
// }
// lisa_touch_bus_config_t bus_config = {
// .bus_type = LISA_TOUCH_BUS_I2C,
// .config = {
// .i2c = {
// .i2c_dev = i2c_dev,
// .int_gpio = gpioa_dev,
// .int_pin = LISA_TOUCH_I2C_INT_PIN,
// .rst_gpio = gpioa_dev,
// .rst_pin = LISA_TOUCH_I2C_RST_PIN,
// }
// }
// };
// int ret = lisa_touch_attach_bus(touch_dev, &bus_config);
// if (ret != 0) {
// printf("Error: Touch bus attach failed (code: %d)\n", ret);
// return -1;
// }
// lv_port_indev_init(touch_dev);
xTaskCreate(task_ui, "task_ui", 4 * 1024, NULL, configMAX_PRIORITIES - 2, NULL);
return 0;
}

View File

@@ -0,0 +1,3 @@
#pragma once
int display_init(void);

View File

@@ -0,0 +1,9 @@
listenai_library_named(fd_image_stream)
listenai_library_sources(
fd_image_stream.c
)
listenai_include_directories(
${CMAKE_CURRENT_SOURCE_DIR}
)

View File

@@ -0,0 +1,93 @@
#include "stdio.h"
#include <string.h>
#include <stdbool.h>
#include "workqueue.h"
#include "acomp_fd.h"
#include "fd_image_stream.h"
#define TAG "fd_image_stream"
#include "lisa_log.h"
/* fd image in stream */
#define FD_IMAGE_FRAME_STREAM_CH_INDEX (0)
#define FD_IMAGE_FRAME_STREAM_CH_CNAME "stream.fd_image"
#define FD_IMAGE_FRAME_STREAM_BUF_SIZE (CONFIG_IMAGE_WIDTH * CONFIG_IMAGE_HEIGHT * 2 + sizeof(acomp_fd_input_frame_t))
static workqueue_t *fd_in_wq = NULL;
int fd_image_stream_init(void)
{
acomp_stream_chn_create_desc_t desc = {
.cname = FD_IMAGE_FRAME_STREAM_CH_CNAME,
.direction = ACOMP_STREAM_DIRECTION_M2R,
.index = FD_IMAGE_FRAME_STREAM_CH_INDEX,
.buffer_size = FD_IMAGE_FRAME_STREAM_BUF_SIZE,
.num_descs = 4,
.kick_policy = 1,
};
fd_in_wq = workqueue_create("fd_in_wq", 9, 10, 8096);
if (fd_in_wq == NULL) {
LISA_LOGE(TAG, "Failed to create fd_in_wq");
}
acomp_fd_stream_ch_enable(FD_IMAGE_FRAME_STREAM_CH_INDEX,&desc);
return 0;
}
static void fd_in_wq_handler(void *para)
{
uint8_t *buffer;
uint32_t buf_size;
uint16_t desc_idx;
acomp_fd_input_frame_t *fd_frame;
static int frame_index = 0;
uint8_t *data = NULL;
video_frame_t *msg = (video_frame_t *)para;
LISA_LOGD(LOG_TAG, "fd_in_wq_handler");
buffer = acomp_fd_stream_tx_buffer_alloc(FD_IMAGE_FRAME_STREAM_CH_INDEX, &buf_size, &desc_idx);
if(buffer && buf_size > 0){
fd_frame = (acomp_fd_input_frame_t *)buffer;
if (msg->format == LISA_CAMERA_PIXFMT_YUV422) {
fd_frame->format = PIX_FMT_YUV422_YUYV_PACKED;
} else if (msg->format == LISA_CAMERA_PIXFMT_RGB565) {
fd_frame->format = PIX_FMT_RGB565;
} else if (msg->format == LISA_CAMERA_PIXFMT_GRAY) {
fd_frame->format = PIX_FMT_GRAY;
}
fd_frame->index = frame_index++;
fd_frame->width = msg->width;
fd_frame->height = msg->height;
fd_frame->length = msg->length;
memcpy(fd_frame->data, msg->buffer, msg->length);
acomp_fd_stream_tx_buffer_submit(FD_IMAGE_FRAME_STREAM_CH_INDEX, buffer, buf_size, desc_idx);
}
msg->func(msg->func_param);
psram_free(msg);
}
int fd_image_stream_send(video_frame_t *data)
{
int ret;
video_frame_t *msg = psram_malloc(sizeof(video_frame_t));
memcpy(msg, data, sizeof(video_frame_t));
ret = workqueue_submit(fd_in_wq, fd_in_wq_handler, msg);
if (ret == 0) {
LISA_LOGE(TAG, "workqueue submit failed:%d", ret);
msg->func(msg->func_param);
psram_free(msg);
}
}

View File

@@ -0,0 +1,19 @@
#pragma once
#include <stdint.h>
#include "lisa_camera.h"
typedef void (*video_frame_release_t)(void *data);
typedef struct {
uint8_t *buffer; /* Frame buffer pointer */
uint32_t length; /* Frame data length */
uint16_t width; /* Frame width */
uint16_t height; /* Frame height */
lisa_camera_pixel_format_t format; /* Pixel format */
video_frame_release_t func; /* camera buffer release function */
void *func_param; /* release function parameters */
} video_frame_t;
int fd_image_stream_init(void);
int fd_image_stream_send(video_frame_t *data);

View File

@@ -0,0 +1,360 @@
#include "stdio.h"
#include <string.h>
#include <stdbool.h>
// module: ic
#include "ic_message.h"
#include "workqueue.h"
#include "acomp.h"
#include "acomp_fd.h"
#include "fd_image_stream.h"
#include "video_camera.h"
#include "display.h"
#include "screen.h"
#include "button.h"
#include "button_adc.h"
#include "adc_key.h"
#define TAG "main"
#include "lisa_log.h"
#define FACE_FEATURE_COMPARE_SCORE_THRESHOLD (1.0f * CONFIG_FACE_COMPARE_SCORE_THRESHOLD / 100)
#define SKIP_FRAME_CNT (((CONFIG_IMAGE_WIDTH == 640) && (CONFIG_IMAGE_HEIGHT == 480)) ? 3 : 2)
typedef struct {
uint32_t index;
button_event_t event;
}key_wq_msg_t;
static workqueue_t *key_wq = NULL;
static void key_wq_handler(void *para);
static uint8_t *image_buf = NULL; /* 实时图片 */
static uint8_t *fd_result1 = NULL; /* 实时人脸识别结果 */
static uint8_t *fd_features = NULL; /* 已注册的人脸特征 */
static int fd_feature_cnt = 0; /* 已注册的人脸特征数量 */
/* 摄像头图片回调 */
static void video_camera_cb(camera_frame_t *frame, void *user_data)
{
(void)user_data;
static uint32_t frame_index = 0;
/* 图片用于屏幕显示 */
memcpy(image_buf, frame->buffer, frame->length);
screen_update_fd_info(NULL, image_buf, CONFIG_IMAGE_WIDTH, CONFIG_IMAGE_HEIGHT, CONFIG_IMAGE_WIDTH * CONFIG_IMAGE_HEIGHT * 2);
if ((++frame_index) % SKIP_FRAME_CNT != 0) {
frame->func(frame->func_param);
return;
}
LISA_LOGD(TAG, "idx:%u, camera buf:%p, len: %d, w:%d, h:%d, f:%d",
(frame_index / SKIP_FRAME_CNT),
frame->buffer,
frame->length,
frame->width,
frame->height,
frame->format);
/* 图片用于人脸识别算法 */
fd_image_stream_send((video_frame_t *)frame);
}
/* 人脸识别结果回调 */
static void fd_event_handler(uint32_t event, void *event_data, uint32_t event_data_len, void *priv)
{
if (event & FD_CB_EVENT_ENGINE_RLT) {
LISA_LOGI(TAG, "fd result:%d,%s", event_data_len, (char *)event_data);
uint8_t *fd_result = psram_malloc_align(32, event_data_len);
if (fd_result == NULL) {
LISA_LOGE(TAG, "%s, %d, malloc len failed", __FUNCTION__, __LINE__);
return;
}
/* 人脸识别结果用于用户来使用(比如用户判断此特征是否符合注册条件,或者是否符合比对条件) */
memcpy(fd_result1, (uint8_t *)event_data, event_data_len);
/* 人脸识别结果显示到屏幕上面 */
memcpy(fd_result, (uint8_t *)event_data, event_data_len);
screen_update_fd_info((acomp_fd_result_info_t *)fd_result, NULL, CONFIG_IMAGE_WIDTH, CONFIG_IMAGE_HEIGHT, CONFIG_IMAGE_WIDTH * CONFIG_IMAGE_HEIGHT * 2);
} else {
LISA_LOGW(TAG, "unknown fd event:0X%X", event);
}
}
/* 按键事件回调 */
static void adc_button_callback(button_event_t evt, button_adc_config_t *user_data)
{
LISA_LOGI(TAG, "adc_button_index: %d, event: %d", user_data->button_index, evt);
if ((evt != LISA_BTN_PRESS_CLICK)
#if CONFIG_ONLY_FACE_REGISTER
|| (user_data->button_index > 1)
#else
|| (user_data->button_index > 2)
#endif
) {
return;
}
key_wq_msg_t *msg = psram_malloc(sizeof(key_wq_msg_t));
if (msg == NULL){
LISA_LOGE(TAG, "%s, %d, malloc failed", __FUNCTION__, __LINE__);
return;
}
msg->index = user_data->button_index;
msg->event = evt;
int ret = workqueue_submit(key_wq, key_wq_handler, msg);
if (ret == 0) {
LISA_LOGE(TAG, "key_wq submit failed:%d", ret);
psram_free(msg);
}
}
static bool is_gray = true;
/* 按键事件处理 */
static void key_wq_handler(void *para)
{
key_wq_msg_t *msg = (key_wq_msg_t *)para;
acomp_fd_result_info_t *info = (acomp_fd_result_info_t *)fd_result1;
if (msg->index == 0) { /* 按键key1用来注册人脸信息 */
uint32_t result_cnt = info->results_cnt;
if (result_cnt > 0) {
uint32_t max_area_index = info->max_area_results_index;
acomp_fd_result_t *result = (acomp_fd_result_t *)&info->results[max_area_index];
float max_register_score = 0;
int index = 0;
LISA_LOGI(TAG, "score: %3f, align_n:%d, head_pose:[%3f, %3f, %3f], live:%d, s[0]:%f, s[1]:%f, feature_cnt:%d, compare_cnt:%d",
result->face_score,
result->n_align_point,
result->pose.yaw,
result->pose.pitch,
result->pose.roll,
result->live_result.status,
result->live_result.scores[0],
result->live_result.scores[1],
result->feature_cnt,
result->compare_cnt
);
/* 判断人脸特征是否满足注册要求(这里仅比较人脸得分、人脸对齐点数、人脸姿态角度,实际应用中可能需要考虑是否是活体、人脸特征点数等) */
if ((result->face_score > 0.8)
&& (result->n_align_point > 0)
&& ((result->pose.yaw < 30.0f) && (result->pose.yaw > -30.0f))
&& ((result->pose.pitch < 30.0f) && (result->pose.pitch > -30.0f))
&& ((result->pose.roll < 30.0f) && (result->pose.roll > -30.0f))
&& (result->live_result.status == 1)
&& (result->feature_cnt > 0)
)
{
/* 如果已经有注册过人脸,需要看是不是同一个人,如果是就不再注册 */
if (result->compare_cnt > 0) {
for (int i = 0; i < result->compare_cnt; i++) {
LISA_LOGI(TAG, "com score[%d]: %f", i, result->compare_scores[i]);
if (result->compare_scores[i] > max_register_score) {
max_register_score = result->compare_scores[i];
index = i;
}
}
LISA_LOGI(TAG, "max score is %f", max_register_score);
/* 判断人脸比较得分是否大于阈值,如果大于阈值,说明是同一个人,不再注册 */
if (max_register_score > FACE_FEATURE_COMPARE_SCORE_THRESHOLD) {
LISA_LOGE(TAG, "this face is already registered, score:%f!", max_register_score);
goto KEY_WQ_ERR;
}
}
if (fd_feature_cnt >= ACOMP_FD_MAX_RESULT_CNT) {
LISA_LOGE(TAG, "register count can't > %d, skip this feature!", ACOMP_FD_MAX_RESULT_CNT);
goto KEY_WQ_ERR;
}
/* 保存人脸特征点 */
acomp_fd_feature_result_t *feature = (acomp_fd_feature_result_t *)(fd_features + sizeof(acomp_fd_feature_result_t) * fd_feature_cnt);
memcpy(&feature->features[0], &result->features[0], sizeof(float) * result->feature_cnt);
feature->feature_cnt = result->feature_cnt;
/* 显示人脸注册数量 */
fd_feature_cnt++;
screen_update_registered(fd_feature_cnt);
LISA_LOGI(TAG, "register ok!");
/* 重新加载已经注册的人脸特征到人脸识别算法 */
if (fd_feature_cnt > 0) {
acomp_fd_features_load((acomp_fd_feature_result_t *)fd_features, fd_feature_cnt);
}
} else {
LISA_LOGE(TAG, "register not ok!");
}
}
} else if (msg->index == 1) { /* 按键key2用来比对人脸信息 */
uint32_t result_cnt = info->results_cnt;
float max_score = 0.0f;
int index = 0;
if (result_cnt > 0) {
uint32_t max_area_index = info->max_area_results_index;
acomp_fd_result_t *result = (acomp_fd_result_t *)&info->results[max_area_index];
LISA_LOGI(TAG, "score: %3f, align_n:%d, head_pose:[%3f, %3f, %3f], live:%d, s[0]:%f, s[1]:%f, feature_cnt:%d, compare_cnt:%d",
result->face_score,
result->n_align_point,
result->pose.yaw,
result->pose.pitch,
result->pose.roll,
result->live_result.status,
result->live_result.scores[0],
result->live_result.scores[1],
result->feature_cnt,
result->compare_cnt
);
/* 先找出最大人脸比对得分(和已有注册人脸的比对得分) */
if (result->compare_cnt > 0) {
for (int i = 0; i < result->compare_cnt; i++) {
LISA_LOGI(TAG, "com score[%d]: %f", i, result->compare_scores[i]);
if (result->compare_scores[i] > max_score) {
max_score = result->compare_scores[i];
index = i;
}
}
}
LISA_LOGI(TAG, "max score is %f", max_score);
/* 然后要判断人脸特征是否满足要求(这里仅比较人脸得分、人脸对齐点数、人脸姿态角度、人脸特征点数、人脸比对个数,实际应用中可能需要考虑是否是活体等) */
if ((result->face_score > 0.8f)
&& (result->n_align_point > 0)
&& ((result->pose.yaw < 30.0f) && (result->pose.yaw > -30.0f))
&& ((result->pose.pitch < 30.0f) && (result->pose.pitch > -30.0f))
&& ((result->pose.roll < 30.0f) && (result->pose.roll > -30.0f))
&& (result->live_result.status == 1)
&& (result->feature_cnt > 0)
&& (result->compare_cnt > 0)
)
{
/* 最大人脸得分是否大于阈值 */
bool flag = (max_score > FACE_FEATURE_COMPARE_SCORE_THRESHOLD) ? true : false;
/* 识别的得分用于屏幕显示 */
screen_update_compare(index, flag, max_score);
} else {
screen_update_compare(index, false, max_score);
LISA_LOGE(TAG, "compare not ok!");
}
}
} else if (msg->index == 2) { /* 按键key3用来切换原图模式和灰度模式 */
LISA_LOGI(TAG, "gray mode: %d", is_gray);
video_camera_set_gray(!is_gray);
is_gray = !is_gray;
}
KEY_WQ_ERR:
psram_free(msg);
}
int main(int argc, char **argv)
{
printf("CP=======! Hard ID: %d\n", CONFIG_HARTID);
ic_message_init();
LISA_LOGI(TAG, "ic_message_init done!");
vTaskDelay(pdMS_TO_TICKS(2000));
/* 存储实时的输入图像 */
image_buf = psram_malloc_align(32, CONFIG_IMAGE_WIDTH * CONFIG_IMAGE_HEIGHT * 2);
if (image_buf == NULL) {
LISA_LOGE(TAG, "%s, %d, malloc len failed", __FUNCTION__, __LINE__);
return -1;
}
/* 存储实时的人脸检测结果 */
fd_result1 = psram_malloc_align(32, sizeof(acomp_fd_result_info_t) + sizeof(acomp_fd_result_t) * ACOMP_FD_MAX_RESULT_CNT);
if (fd_result1 == NULL) {
LISA_LOGE(TAG, "%s, %d, malloc len failed", __FUNCTION__, __LINE__);
return -1;
}
/* 存储注册的人脸特征 */
fd_features = psram_malloc_align(32, sizeof(acomp_fd_feature_result_t) * ACOMP_FD_MAX_RESULT_CNT);
if (fd_features == NULL) {
LISA_LOGE(TAG, "%s, %d, malloc len failed", __FUNCTION__, __LINE__);
return -1;
}
/* 算法组件初始化 */
acomp_init();
/* 人脸识别算法模块 */
acomp_fd_init();
acomp_fd_prepare();
acomp_fd_start();
acomp_fd_add_callback(FD_CB_EVENT_ENGINE_RLT, fd_event_handler, NULL);
const acomp_fd_param_t param = {
.key = PARAM_DETECT_OUT_THRES,
.value = 0.7f,
};
acomp_fd_params_set(&param, 1);
#if CONFIG_FACE_LIVE_DETECT_ENABLE
const acomp_fd_live_detect_mode_t mode = {
.enable = true, // 启用活体检测
.score_threshold = {
0.5f, // 非活体得分阈值(实际没用到这个参数)
1.0f * CONFIG_FACE_LIVE_DETECT_THRESHOLD / 100, // 活体得分阈值(如果活体得分大于等于这个阈值, 就继续进行人脸特征提取和人脸识别)
},
};
acomp_fd_live_detect_mode_set(&mode);
#endif
/* 人脸图片输入流初始化 */
fd_image_stream_init();
/* 屏幕显示模块 */
display_init();
/* 按键模块 */
key_wq = workqueue_create("key_wq", 9, 10, 8192);
if (key_wq == NULL) {
LISA_LOGE(TAG, "Failed to create key_wq");
}
test_adc_button(adc_button_callback);
/* 摄像头模块 */
camera_config_t config = {
.width = CONFIG_IMAGE_WIDTH,
.height = CONFIG_IMAGE_HEIGHT,
.format = CONFIG_IMAGE_FORMAT,
};
video_camera_init(&config);
video_camera_register_callback(video_camera_cb, NULL);
video_camera_start_capture();
while(1){
vTaskDelay(pdMS_TO_TICKS(1000));
}
return 0;
}

View File

@@ -0,0 +1,9 @@
listenai_library_named(screen)
listenai_library_sources(
screen.c
)
listenai_include_directories(
${CMAKE_CURRENT_SOURCE_DIR}
)

View File

@@ -0,0 +1,385 @@
/*
* Copyright (c) 2026 Anhui Listenai Co., Ltd.
* SPDX-License-Identifier: Apache-2.0
*/
#include "stdio.h"
#include <string.h>
#include <stdbool.h>
#include "workqueue.h"
#include "screen.h"
#define TAG "screen"
#include "lisa_log.h"
#define REAL_TIME_COMPARE_STATUS (CONFIG_ONLY_FACE_REGISTER)
#define COMPARE_SCORE_THRESHOLD (1.0f * CONFIG_FACE_COMPARE_SCORE_THRESHOLD / 100)
#define DISPLAY_WIDTH CONFIG_PANEL_ST7789P3_HEIGHT
#define DISPLAY_HEIGHT CONFIG_PANEL_ST7789P3_WIDTH
#define PREVIEW_WIDTH (DISPLAY_WIDTH)
#define PREVIEW_HEIGHT (DISPLAY_HEIGHT)
#define SPAN(n) (8 * n)
#define BIT_MASK(n) ((1 << (n)) - 1)
#define COLOR_RED (lv_color_hex(0xFF0000))
#define COLOR_GREEN (lv_color_hex(0x00FF00))
#define COLOR_YELLOW (lv_color_hex(0xFFCC00))
#define COLOR_WHITE (lv_color_hex(0x999999))
#define MAX_RESULT_CNT (5)
static lv_obj_t *preview;
static lv_obj_t *preview;
static lv_obj_t *face_rect;
static lv_obj_t *detect_status;
#if REAL_TIME_COMPARE_STATUS
static lv_obj_t *compare_status;
#endif
static lv_obj_t *verify_status;
static lv_obj_t *register_status;
static lv_img_dsc_t preview_img;
static __attribute__((section(".psram.bss"))) uint16_t preview_buf[PREVIEW_WIDTH * PREVIEW_HEIGHT];
typedef struct {
acomp_fd_result_info_t *info;
uint8_t *img_data;
uint16_t img_width;
uint16_t img_height;
uint32_t img_len;
}screen_msg_t;
static workqueue_t *screen_wq = NULL;
lv_obj_t *screen_create(void)
{
lv_obj_t *screen = lv_obj_create(NULL);
lv_obj_set_scrollbar_mode(screen, LV_SCROLLBAR_MODE_OFF);
preview = lv_img_create(screen);
lv_obj_set_pos(preview, 0, 0);
lv_obj_set_size(preview, PREVIEW_WIDTH, PREVIEW_HEIGHT);
lv_obj_t *guide = lv_label_create(screen);
lv_obj_set_style_text_color(guide, COLOR_RED, LV_PART_MAIN);
lv_obj_set_size(guide, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_align(guide, LV_ALIGN_BOTTOM_MID, 0, SPAN(-1));
lv_label_set_text_static(guide, "K1: REGISTER "
#if REAL_TIME_COMPARE_STATUS == 0
"| K2: RECOGNIZE"
#endif
#if defined(CONFIG_FD_ANTI_SPOOFING)
" | K3: IR"
#endif /* CONFIG_FD_ANTI_SPOOFING */
);
face_rect = lv_obj_create(screen);
lv_obj_set_style_bg_opa(face_rect, LV_OPA_TRANSP, LV_PART_MAIN);
lv_obj_set_style_border_width(face_rect, 1, LV_PART_MAIN);
lv_obj_set_style_border_color(face_rect, COLOR_YELLOW, LV_PART_MAIN);
lv_obj_set_style_radius(face_rect, 0, LV_PART_MAIN);
lv_obj_add_flag(face_rect, LV_OBJ_FLAG_HIDDEN);
detect_status = lv_label_create(screen);
lv_obj_set_style_text_color(detect_status, COLOR_WHITE, LV_PART_MAIN);
lv_obj_set_size(detect_status, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_align(detect_status, LV_ALIGN_TOP_LEFT, SPAN(1), SPAN(1));
lv_label_set_text(detect_status, "has_face: 0");
#if REAL_TIME_COMPARE_STATUS
compare_status = lv_label_create(screen);
lv_obj_set_style_text_color(compare_status, COLOR_WHITE, LV_PART_MAIN);
lv_obj_set_size(compare_status, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_align(compare_status, LV_ALIGN_TOP_LEFT, SPAN(1), SPAN(3));
lv_label_set_text(compare_status, "compare: id: 0, score: 0");
lv_obj_add_flag(compare_status, LV_OBJ_FLAG_HIDDEN);
#endif
verify_status = lv_label_create(screen);
lv_obj_set_style_text_color(verify_status, COLOR_YELLOW, LV_PART_MAIN);
lv_obj_set_size(verify_status, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_align(verify_status, LV_ALIGN_BOTTOM_LEFT, SPAN(1), SPAN(-6));
lv_label_set_text(verify_status, "----");
register_status = lv_label_create(screen);
lv_obj_set_style_text_color(register_status, COLOR_YELLOW, LV_PART_MAIN);
lv_obj_set_size(register_status, LV_SIZE_CONTENT, LV_SIZE_CONTENT);
lv_obj_align(register_status, LV_ALIGN_BOTTOM_LEFT, SPAN(1), SPAN(-4));
lv_label_set_text(register_status, "registered: 0");
preview_img.header.cf = LV_IMG_CF_TRUE_COLOR;
preview_img.header.w = PREVIEW_WIDTH;
preview_img.header.h = PREVIEW_HEIGHT;
preview_img.data = (uint8_t *)preview_buf;
preview_img.data_size = sizeof(preview_buf);
screen_wq = workqueue_create("screen_wq", 9, 10, 8096);
if (screen_wq == NULL) {
LISA_LOGE(TAG, "Failed to create screen_wq");
}
return screen;
}
static inline uint16_t yuyv_to_rgb565(uint8_t y, uint8_t u, uint8_t v)
{
int r, g, b;
int c = y - 16;
int d = u - 128;
int e = v - 128;
r = (298 * c + 409 * e + 128) >> 8;
g = (298 * c - 100 * d - 208 * e + 128) >> 8;
b = (298 * c + 516 * d + 128) >> 8;
r = r < 0 ? 0 : (r > 255 ? 255 : r);
g = g < 0 ? 0 : (g > 255 ? 255 : g);
b = b < 0 ? 0 : (b > 255 ? 255 : b);
return ((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3);
}
/**
* @brief 进行图片缩放,以及YUYV422转RGB565
*
* @param img_data[in] 人脸图像数据
* @param img_width[in] 图像宽度
* @param img_height[in] 图像高度
* @param img_len[in] 图像长度
* @param output_buf[out] 输出图像缓存
*
* @return void
*
*/
static void process_image(uint8_t *img_data, int img_width, int img_height, int img_len, uint16_t *output_buf)
{
bool is_yuyv = (CONFIG_IMAGE_FORMAT == 2);
bool need_scale = false;
if ((img_width == 160 && img_height == 120) ||
(img_width == 640 && img_height == 480)) {
need_scale = true;
}
if (is_yuyv) {
if (need_scale) {
if (img_width == 160 && img_height == 120) {
for (int y = 0; y < 240; y++) {
for (int x = 0; x < 320; x++) {
int src_x = x / 2;
int src_y = y / 2;
int pixel_pair_idx = src_y * 160 + (src_x & ~1);
int byte_idx = pixel_pair_idx * 2;
uint8_t y_val = img_data[byte_idx + (src_x & 1) * 2];
uint8_t u_val = img_data[byte_idx + 1];
uint8_t v_val = img_data[byte_idx + 3];
output_buf[y * 320 + x] = yuyv_to_rgb565(y_val, u_val, v_val);
}
}
} else if (img_width == 640 && img_height == 480) {
for (int y = 0; y < 240; y++) {
for (int x = 0; x < 320; x++) {
int src_x = x * 2;
int src_y = y * 2;
int pixel_pair_idx = src_y * 640 + (src_x & ~1);
int byte_idx = pixel_pair_idx * 2;
uint8_t y_val = img_data[byte_idx + (src_x & 1) * 2];
uint8_t u_val = img_data[byte_idx + 1];
uint8_t v_val = img_data[byte_idx + 3];
output_buf[y * 320 + x] = yuyv_to_rgb565(y_val, u_val, v_val);
}
}
}
} else if (img_width == 320 && img_height == 240) {
for (int i = 0; i < img_width * img_height / 2; i++) {
int byte_idx = i * 4;
uint8_t y0 = img_data[byte_idx];
uint8_t u = img_data[byte_idx + 1];
uint8_t y1 = img_data[byte_idx + 2];
uint8_t v = img_data[byte_idx + 3];
output_buf[i * 2] = yuyv_to_rgb565(y0, u, v);
output_buf[i * 2 + 1] = yuyv_to_rgb565(y1, u, v);
}
} else {
for (int i = 0; i < img_width * img_height / 2; i++) {
int byte_idx = i * 4;
uint8_t y0 = img_data[byte_idx];
uint8_t u = img_data[byte_idx + 1];
uint8_t y1 = img_data[byte_idx + 2];
uint8_t v = img_data[byte_idx + 3];
output_buf[i * 2] = yuyv_to_rgb565(y0, u, v);
output_buf[i * 2 + 1] = yuyv_to_rgb565(y1, u, v);
}
}
} else {
if (need_scale) {
if (img_width == 160 && img_height == 120) {
uint16_t *src = (uint16_t *)img_data;
for (int y = 0; y < 240; y++) {
for (int x = 0; x < 320; x++) {
int src_x = x / 2;
int src_y = y / 2;
output_buf[y * 320 + x] = src[src_y * 160 + src_x];
}
}
} else if (img_width == 640 && img_height == 480) {
uint16_t *src = (uint16_t *)img_data;
for (int y = 0; y < 240; y++) {
for (int x = 0; x < 320; x++) {
int src_x = x * 2;
int src_y = y * 2;
output_buf[y * 320 + x] = src[src_y * 640 + src_x];
}
}
}
} else {
memcpy(output_buf, img_data, img_len);
}
}
}
void screen_update_info(const acomp_fd_result_info_t *info, uint8_t *img_data, int img_width, int img_height, int img_len)
{
if (img_data) {
process_image(img_data, img_width, img_height, img_len, preview_buf);
lv_img_set_src(preview, &preview_img);
}
if (info) {
uint32_t result_cnt = info->results_cnt;
if (result_cnt > 0) {
uint32_t max_area_index = info->max_area_results_index;
acomp_fd_result_t *result = (acomp_fd_result_t *)&info->results[max_area_index];
/* 人脸个数,活体状态和分数 */
char live_score[64] = {0};
memset(live_score, 0, sizeof(live_score));
snprintf(live_score, sizeof(live_score), "%.6f", result->live_result.scores[1]);
lv_label_set_text_fmt(detect_status, "has_face: %d, Live: %d, LiveScore: %s", result_cnt, result->live_result.status, live_score);
/* 最大匹配得分 */
#if REAL_TIME_COMPARE_STATUS
int max_score_index = 0;
float max_score = 0.0f;
if (result->compare_cnt > 0) {
for (int i = 0; i < result->compare_cnt; i++) {
if (result->compare_scores[i] > max_score) {
max_score = result->compare_scores[i];
max_score_index = i;
}
}
char max_score_str[64] = {0};
memset(max_score_str, 0, 64);
snprintf(max_score_str, 64, "%.3f", max_score);
lv_label_set_text_fmt(compare_status, "compare: id: %d, score: %s", max_score_index, max_score_str);
lv_obj_clear_flag(compare_status, LV_OBJ_FLAG_HIDDEN);
bool pass = (max_score > COMPARE_SCORE_THRESHOLD ? true : false);
lv_obj_set_style_border_color(face_rect, pass ? COLOR_GREEN : COLOR_RED, LV_PART_MAIN);
}
#endif
/* 人脸方框 */
float scale_x = 1.0f;
float scale_y = 1.0f;
if (img_width == 160 && img_height == 120) {
scale_x = 320.0f / 160.0f;
scale_y = 240.0f / 120.0f;
} else if (img_width == 640 && img_height == 480) {
scale_x = 320.0f / 640.0f;
scale_y = 240.0f / 480.0f;
}
int scaled_x = (int)(result->face_rect.x * scale_x);
int scaled_y = (int)(result->face_rect.y * scale_y);
int scaled_w = (int)(result->face_rect.w * scale_x);
int scaled_h = (int)(result->face_rect.h * scale_y);
lv_obj_set_pos(face_rect, scaled_x, scaled_y);
lv_obj_set_size(face_rect, scaled_w, scaled_h);
lv_obj_clear_flag(face_rect, LV_OBJ_FLAG_HIDDEN);
} else {
lv_label_set_text_fmt(detect_status, "has_face: %d", 0);
lv_obj_add_flag(face_rect, LV_OBJ_FLAG_HIDDEN);
lv_label_set_text(verify_status, "----");
lv_obj_set_style_text_color(verify_status, COLOR_YELLOW, LV_PART_MAIN);
lv_obj_set_style_text_color(register_status, COLOR_YELLOW, LV_PART_MAIN);
lv_obj_set_style_border_color(face_rect, COLOR_YELLOW, LV_PART_MAIN);
#if REAL_TIME_COMPARE_STATUS
lv_obj_add_flag(compare_status, LV_OBJ_FLAG_HIDDEN);
#endif
}
}
#if defined(CONFIG_DISPLAY_DEBUG_SHOW_FPS)
frame_cnt++;
#endif /* CONFIG_DISPLAY_DEBUG_SHOW_FPS */
}
static void screen_wq_handler(void *para)
{
screen_msg_t *msg = (screen_msg_t *)para;
LISA_LOGD(LOG_TAG, "screen_wq_handler");
screen_update_info(msg->info, msg->img_data, msg->img_width, msg->img_height, msg->img_len);
if(msg->info) {
psram_free(msg->info);
}
psram_free(msg);
}
void screen_update_fd_info(acomp_fd_result_info_t *info, uint8_t *img_data, int img_width, int img_height, int img_len)
{
screen_msg_t *msg = (screen_msg_t *)psram_malloc(sizeof(screen_msg_t));
msg->info = info;
msg->img_data = img_data;
msg->img_width = img_width;
msg->img_height = img_height;
msg->img_len = img_len;
int ret = workqueue_submit(screen_wq, screen_wq_handler, msg);
if (ret == 0) {
LISA_LOGE(TAG, "workqueue submit failed:%d", ret);
if(msg->info) {
psram_free(msg->info);
}
psram_free(msg);
}
}
void screen_update_registered(uint32_t count)
{
lv_label_set_text_fmt(register_status, "registered: %d", count);
}
static char score_str[256] = {0};
void screen_update_compare(uint32_t index, bool pass, float score)
{
memset(score_str, 0, 256);
snprintf(score_str, 256, "%.4f", score);
LISA_LOGI(TAG, "screen_update_compare: index: %d, score: %f, score_str: %s, pass: %d", index, score, score_str, pass);
lv_label_set_text_fmt(verify_status, "id: %d, score: %s", index, score_str);
lv_obj_set_style_text_color(verify_status, pass ? COLOR_GREEN : COLOR_RED, LV_PART_MAIN);
lv_obj_set_style_text_color(register_status, pass ? COLOR_GREEN : COLOR_RED, LV_PART_MAIN);
lv_obj_set_style_border_color(face_rect, pass ? COLOR_GREEN : COLOR_RED, LV_PART_MAIN);
}

View File

@@ -0,0 +1,64 @@
/*
* Copyright (c) 2023 Anhui Listenai Co., Ltd.
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <stdint.h>
#include <float.h>
#include <lvgl.h>
#include "acomp_fd.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief 创建屏幕组件
*
* @return lv_obj_t* 创建的屏幕对象
*
*/
lv_obj_t *screen_create(void);
/**
* @brief 更新人脸图片或人脸检测结果到屏幕
*
* @param info[in] 人脸检测结果信息
* @param img_data[in] 人脸图像数据
* @param img_width[in] 图像宽度
* @param img_height[in] 图像高度
* @param img_len[in] 图像长度
*
* @return void
*
*/
void screen_update_fd_info(acomp_fd_result_info_t *info, uint8_t *img_data, int img_width, int img_height, int img_len);
/**
* @brief 更新已注册的人脸个数到屏幕
*
* @param count[in] 已注册的人脸个数
*
* @return void
*
*/
void screen_update_registered(uint32_t count);
/**
* @brief 更新人脸特征比较结果到屏幕
*
* @param index[in] 已注册的人脸索引
* @param pass[in] 是否通过
* @param score[in] 比较得分
*
* @return void
*
*/
void screen_update_compare(uint32_t index, bool pass, float score);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,11 @@
.. _demos:
demo示例
========
本目录包含完整的演示示例,展示如何使用 ARCS SDK 的各种功能构建实际应用。
.. toctree::
:maxdepth: 1
face_detect/README.md