上一章的電容按鍵完全使用的HAL庫的代碼,并沒有使用線程。這里嘗試使用線程來控制電容按鍵。
依舊是 F767
本來以為會很容易實現,沒想到嘗試了很久,電容按鍵一直沒有反應。
static rt_uint32_t measure_charge_time(void)
{// 步驟1: 放電 (PA5輸出低電平)rt_pin_mode(CAP_KEY_PIN, PIN_MODE_OUTPUT);rt_pin_write(CAP_KEY_PIN, PIN_LOW);rt_hw_us_delay(200); // 充分放電// 步驟2: 切換到輸入捕獲模式rt_pin_mode(CAP_KEY_PIN, PIN_MODE_INPUT);// 步驟3: 重置計數器并啟動捕獲__HAL_TIM_SET_COUNTER(&htim2, 0);HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL);// 步驟4: 開始充電rt_pin_write(CAP_KEY_PIN, PIN_HIGH);rt_hw_us_delay(1); // 確保充電開始// 等待捕獲完成 (等待10ms)rt_uint32_t start_tick = rt_tick_get();while (__HAL_TIM_GET_FLAG(&htim2, TIM_FLAG_CC1) == RESET) {if ((rt_tick_get() - start_tick) > rt_tick_from_millisecond(10)) {break;}}// 獲取捕獲值rt_uint32_t capture_value = HAL_TIM_ReadCapturedValue(&htim2, TIM_CHANNEL);HAL_TIM_IC_Stop_IT(&htim2, TIM_CHANNEL);// 清除捕獲標志__HAL_TIM_CLEAR_FLAG(&htim2, TIM_FLAG_CC1);return capture_value;
}
上面這一段是原來的,按鍵捕獲函數,也就是靠 這段代碼來捕獲PA5的上升沿。
然后,函數卡在了
這部分。這是為什么呢?邏輯上沒有什么問題。其實很簡單,充電錯了:
這里是有3.3V電源的。所以不應該 通過PA5充電。
那我們改成PIN_LOW.對嗎?
還是不對,要通過使用TIM得到電容按鍵的充電時間,就需要捕捉上升沿,我們下拉引腳是得不到上升沿的,所以,我們這里需要NOPULL。
可是。。。RTthread的PIN模式里面竟然沒有NOPULL
原來是RT直接將 INPUT拆分了。PIN_MODE_INPUT,就是NOPULL。看來我的基礎 還需要鞏固,引腳的電平模式都還沒有區分清楚。
按照上一章配置RTthread后,接下來就是完整的代碼:
Tpad_tim2.c:
#include <rtthread.h>
#include <rthw.h>
#include <board.h>
#include <rtdevice.h>
#include <drv_common.h>
//#include <tim.h> // 包含STM32Cube HAL的TIM頭文件// 硬件配置
#define CAP_KEY_PIN GET_PIN(A, 5) // PA5引腳
#define TIM_CHANNEL TIM_CHANNEL_1 // TIM2_CH1// 軟件配置
#define SAMPLE_INTERVAL 20 // 采樣間隔(ms)
#define TOUCH_THRESHOLD 1.2 // 觸發閾值倍數
#define CALIBRATION_COUNT 50 // 校準采樣次數
#define MAX_CHARGE_TIME 5000 // 最大充電時間(us)static TIM_HandleTypeDef htim2;// 全局狀態變量
static rt_uint32_t baseline = 0; // 基準電容值(無觸摸)
static struct rt_timer touch_timer; // 觸摸定時器
static rt_bool_t touched = RT_FALSE; // 當前觸摸狀態// 回調函數指針
static void (*key_press_callback)(void) = RT_NULL;
static void (*key_release_callback)(void) = RT_NULL;/*** @brief 設置按鍵回調函數* @param press_cb 按鍵按下回調函數* @param release_cb 按鍵釋放回調函數*/
void cap_key_set_callback(void (*press_cb)(void), void (*release_cb)(void))
{key_press_callback = press_cb;key_release_callback = release_cb;
}/*** @brief 初始化TIM2輸入捕獲*/
static void tim2_capture_init(void)
{// 1. 使能TIM2時鐘__HAL_RCC_TIM2_CLK_ENABLE();// 2. 配置基礎定時器設置htim2.Instance = TIM2;htim2.Init.Prescaler = 84 - 1; // 84MHz/84 = 1MHz (1us精度)htim2.Init.CounterMode = TIM_COUNTERMODE_UP;htim2.Init.Period = 0xFFFF;htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;if (HAL_TIM_IC_Init(&htim2) != HAL_OK) {rt_kprintf("TIM2 init failed!\n");return;}// 3. 配置輸入捕獲通道TIM_IC_InitTypeDef sConfigIC = {0};sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_RISING;sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI;sConfigIC.ICPrescaler = TIM_ICPSC_DIV1;sConfigIC.ICFilter = 0;if (HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL) != HAL_OK) {rt_kprintf("TIM2 channel config failed!\n");return;}// 4. 配置GPIO引腳復用GPIO_InitTypeDef GPIO_InitStruct = {0};__HAL_RCC_GPIOA_CLK_ENABLE();GPIO_InitStruct.Pin = GPIO_PIN_5;GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;GPIO_InitStruct.Pull = GPIO_NOPULL;GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;GPIO_InitStruct.Alternate = GPIO_AF1_TIM2;HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);// 5. 配置中斷HAL_NVIC_SetPriority(TIM2_IRQn, 2, 0);HAL_NVIC_EnableIRQ(TIM2_IRQn);// 6. 啟動定時器基礎計數HAL_TIM_Base_Start(&htim2);rt_kprintf("TIM2 capture initialized\n");
}/*** @brief 測量充電時間(單位:us)** 使用TIM2的輸入捕獲功能測量PA5的充電時間*/
static rt_uint32_t measure_charge_time(void)
{GPIO_InitTypeDef GPIO_InitStruct = {0};// 步驟1: 放電 (PA5輸出低電平)rt_pin_mode(CAP_KEY_PIN, PIN_MODE_OUTPUT);rt_pin_write(CAP_KEY_PIN, PIN_LOW);rt_hw_us_delay(200); // 充分放電// 步驟2: 切換到輸入捕獲模式rt_pin_mode(CAP_KEY_PIN, PIN_MODE_INPUT);// 步驟3: 重置計數器并啟動捕獲__HAL_TIM_SET_COUNTER(&htim2, 0);HAL_TIM_IC_Start_IT(&htim2, TIM_CHANNEL_1);// 步驟4: 開始充電//rt_pin_mode(CAP_KEY_PIN, PIN_MODE_INPUT);GPIO_InitStruct.Pin = GPIO_PIN_5;GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;GPIO_InitStruct.Alternate = GPIO_AF1_TIM2;GPIO_InitStruct.Pull = GPIO_NOPULL;GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);rt_hw_us_delay(1); // 確保充電開始// 等待捕獲完成 (等待10ms)rt_uint32_t start_tick = rt_tick_get();while (__HAL_TIM_GET_FLAG(&htim2, TIM_FLAG_CC1) == RESET) {// 超時保護if ((rt_tick_get() - start_tick) > rt_tick_from_millisecond(10)) {rt_kprintf("Capture timeout! Counter: %d\n", __HAL_TIM_GET_COUNTER(&htim2));break;}}// 獲取捕獲值rt_uint32_t capture_value = HAL_TIM_ReadCapturedValue(&htim2, TIM_CHANNEL);HAL_TIM_IC_Stop_IT(&htim2, TIM_CHANNEL);// 清除捕獲標志__HAL_TIM_CLEAR_FLAG(&htim2, TIM_FLAG_CC1);return capture_value;
}/*** @brief 高級校準算法*/
static void advanced_calibration(void)
{rt_uint32_t samples[CALIBRATION_COUNT];rt_uint32_t min = 0xFFFFFFFF, max = 0;rt_uint32_t sum = 0;// 第一階段:采集原始樣本for (int i = 0; i < CALIBRATION_COUNT; i++) {samples[i] = measure_charge_time();if (samples[i] < min) min = samples[i];if (samples[i] > max) max = samples[i];sum += samples[i];rt_thread_mdelay(10);}// 第二階段:剔除異常值(20%邊界)rt_uint32_t range = max - min;rt_uint32_t low_bound = min + range / 5;rt_uint32_t high_bound = max - range / 5;rt_uint32_t valid_sum = 0;rt_uint16_t valid_count = 0;for (int i = 0; i < CALIBRATION_COUNT; i++) {if (samples[i] >= low_bound && samples[i] <= high_bound) {valid_sum += samples[i];valid_count++;}}// 第三階段:設定基準值if (valid_count > (CALIBRATION_COUNT / 3)) {baseline = valid_sum / valid_count;rt_kprintf("Calibrated baseline: %d us\n", baseline);} else {baseline = (min + max) / 2;rt_kprintf("Fallback baseline: %d us\n", baseline);}
}/*** @brief 觸摸檢測定時器回調函數*/
static void touch_timer_handler(void *parameter)
{rt_uint32_t current_value = measure_charge_time();// 調試輸出static int count = 0;if (++count % 1000 == 0) { // 每1000次采樣輸出一次rt_kprintf("[%d] Current: %d us, Baseline: %d us, Threshold: %d us\n",count, current_value, baseline, (rt_uint32_t)(baseline * TOUCH_THRESHOLD));}// 檢測觸摸if (current_value > (rt_uint32_t)(baseline * TOUCH_THRESHOLD) &¤t_value < MAX_CHARGE_TIME) {if (!touched) {touched = RT_TRUE;rt_kprintf("TOUCH detected! Value: %d us\n", current_value);// 調用按鍵按下回調if (key_press_callback) {rt_kprintf("Calling press callback\n");key_press_callback();}}} else {if (touched) {touched = RT_FALSE;rt_kprintf("Touch released\n");// 調用按鍵釋放回調if (key_release_callback) {rt_kprintf("Calling release callback\n");key_release_callback();}}}
}/*** @brief 初始化電容按鍵功能*/
int cap_key_init(void)
{// 初始化TIM2捕獲功能tim2_capture_init();// 初始校準advanced_calibration();// 創建觸摸檢測定時器rt_timer_init(&touch_timer,"touch_timer",touch_timer_handler,RT_NULL,rt_tick_from_millisecond(SAMPLE_INTERVAL),RT_TIMER_FLAG_PERIODIC | RT_TIMER_FLAG_HARD_TIMER);rt_timer_start(&touch_timer);rt_kprintf("Capacitive key (PA5) initialized!\n");return RT_EOK;
}
INIT_APP_EXPORT(cap_key_init);// 調試命令
static void cap_debug(int argc, char *argv[])
{if (argc > 1) {if (rt_strcmp(argv[1], "measure") == 0) {rt_kprintf("Current value: %d us\n", measure_charge_time());}else if (rt_strcmp(argv[1], "calibrate") == 0) {advanced_calibration();}} else {rt_kprintf("Usage:\n");rt_kprintf("cap_debug measure - Get current value\n");rt_kprintf("cap_debug calibrate - Recalibrate sensor\n");}
}
MSH_CMD_EXPORT(cap_debug, Capacitive key debug tool);/*** @brief TIM2中斷處理函數*/
//void TIM2_IRQHandler(void)
//{
// HAL_TIM_IRQHandler(&htim2);
//}
Tpad_tim2.h:
/** Copyright (c) 2006-2021, RT-Thread Development Team** SPDX-License-Identifier: Apache-2.0** Change Logs:* Date Author Notes* 2025-06-26 c the first version*/
#ifndef APPLICATIONS_TPAD_TIM2_H_
#define APPLICATIONS_TPAD_TIM2_H_void cap_key_set_callback(void (*press_cb)(void), void (*release_cb)(void));#endif /* APPLICATIONS_TPAD_TIM2_H_ */
main.c:
#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include <Tpad_tim2.h>#define DBG_TAG "main"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>#define LED_G_PIN GET_PIN(H, 11)// 按鍵按下處理
static void on_key_press(void)
{rt_kprintf("PRESS\n");rt_pin_mode(LED_G_PIN, PIN_MODE_OUTPUT);rt_pin_write(LED_G_PIN, PIN_LOW);// 執行操作,如點亮LED
}// 按鍵釋放處理
static void on_key_release(void)
{rt_kprintf("RELEASE\n");rt_pin_mode(LED_G_PIN, PIN_MODE_OUTPUT);rt_pin_write(LED_G_PIN, PIN_HIGH);
}int main(void)
{// 設置回調函數cap_key_set_callback(on_key_press, on_key_release);while (1) {rt_thread_mdelay(1000);rt_kprintf("on...\n");}return 0;
}
運行下載后,當手指放上去時,會亮綠燈,手指離開會熄滅。終端也會打印對應的信息。