- 測量按鍵按下時(shí)長思路


- 測量按鍵按下時(shí)間實(shí)驗(yàn)?zāi)康?/strong>
使用定時(shí)器 2 通道 2 來捕獲按鍵 (按鍵接PA0)按下時(shí)間,并通過串口打印。
計(jì)一個(gè)數(shù)的時(shí)間:1us,PSC=71,ARR=65535
下降沿捕獲、輸入通道 2 映射在 TI2 上、不分頻、不濾波

1.硬件
- STM32單片機(jī)最小系統(tǒng)
- 按鍵模塊
2.軟件
- 定時(shí)器HAL驅(qū)動(dòng)層文件添加
- ic驅(qū)動(dòng)文件添加
- GPIO常用函數(shù)
- 定時(shí)器輸入捕獲實(shí)驗(yàn)配置步驟
- main.c程序
#include "sys.h"
#include "delay.h"
#include "led.h"
#include "uart1.h"
#include "ic.h"int main(void)
{HAL_Init(); stm32_clock_init(RCC_PLL_MUL9); led_init(); uart1_init(115200);printf("hello world!\r\n");ic_init(65536 - 1, 72 - 1);while(1){ led1_on();led2_off();delay_ms(500);led1_off();led2_on();delay_ms(500);}
}
- **
ic_init(65536 - 1, 72 - 1);//計(jì)時(shí)1us
**語句定時(shí)參考

#include "ic.h"
#include "stdio.h"TIM_HandleTypeDef ic_handle = {0};
void ic_init(uint16_t arr, uint16_t psc)
{TIM_IC_InitTypeDef ic_config = {0};ic_handle.Instance = TIM2;ic_handle.Init.Prescaler = psc;ic_handle.Init.Period = arr;ic_handle.Init.CounterMode = TIM_COUNTERMODE_UP;HAL_TIM_IC_Init(&ic_handle);ic_config.ICPolarity = TIM_ICPOLARITY_FALLING;ic_config.ICSelection = TIM_ICSELECTION_DIRECTTI;ic_config.ICPrescaler = TIM_ICPSC_DIV1;ic_config.ICFilter = 0;HAL_TIM_IC_ConfigChannel(&ic_handle, &ic_config, TIM_CHANNEL_2);__HAL_TIM_ENABLE_IT(&ic_handle, TIM_IT_UPDATE);HAL_TIM_IC_Start_IT(&ic_handle, TIM_CHANNEL_2);
}void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim)
{if(htim->Instance == TIM2){GPIO_InitTypeDef gpio_initstruct;__HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_TIM2_CLK_ENABLE();gpio_initstruct.Pin = GPIO_PIN_0; gpio_initstruct.Mode = GPIO_MODE_AF_PP; gpio_initstruct.Pull = GPIO_PULLUP; gpio_initstruct.Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init(GPIOB, &gpio_initstruct);HAL_NVIC_SetPriority(TIM2_IRQn, 2, 2);HAL_NVIC_EnableIRQ(TIM2_IRQn);}
}void TIM2_IRQHandler(void)
{HAL_TIM_IRQHandler(&ic_handle);
}void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim)
{printf("捕獲到下降沿\r\n");
}
#ifndef __IC_H__
#define __IC_H__#include "sys.h"
void ic_init(uint16_t arr, uint16_t psc);#endif
3.實(shí)物效果
- 硬件模塊接線
KEY一端—>PA0
KEY另一端—>GND
ST-Link下載方式
打開串口軟件,當(dāng)按鍵按下時(shí),串口打印輸出“捕獲到下降沿”