目录
概述
一、开发环境
二、STM32CubeMx配置
三、编码
四、运行结果
五、总结
概述
本文章使用最简单的写法实现长、短、多击按键框架,非常适合移植各类型单片机,特别是资源少的芯片上。接下来将在stm32单片机上实现,只需占用1个定时器作为时钟扫描按键即可。
一、开发环境
1、硬件平台
STM32F401CEU6
内部Flash : 512Kbytes,SARM : 96 Kbytes
二、STM32CubeMx配置
2.1、系统时钟配置
2.2、下载调试配置
2.3、TIM配置(1ms中断)
2.4、usart1配置
2.5、生成代码
2.6、编译工程
三、编码
1、usart.c添加打印
/* USER CODE BEGIN 1 */
#include "stdio.h"
#ifdef __GNUC__
/* With GCC/RAISONANCE, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/**
* @brief Retargets the C library printf function to the USART.
* @param None
* @retval None
*/
PUTCHAR_PROTOTYPE
{
/* Place your implementation of fputc here */
/* e.g. write a character to the EVAL_COM1 and Loop until the end of transmission */
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
int fgetc(FILE * f)
{
uint8_t ch = 0;
HAL_UART_Receive(&huart1, (uint8_t *)&ch, 1, 0xffff);
return ch;
}
/* USER CODE END 1 */
2、tim1.c
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file tim.c
* @brief This file provides code for the configuration
* of the TIM instances.
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "tim.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
TIM_HandleTypeDef htim1;
/* TIM1 init function */
void MX_TIM1_Init(void)
{
/* USER CODE BEGIN TIM1_Init 0 */
/* USER CODE END TIM1_Init 0 */
TIM_ClockConfigTypeDef sClockSourceConfig = {0};
TIM_MasterConfigTypeDef sMasterConfig = {0};
/* USER CODE BEGIN TIM1_Init 1 */
/* USER CODE END TIM1_Init 1 */
htim1.Instance = TIM1;
htim1.Init.Prescaler = 84-1;
htim1.Init.CounterMode = TIM_COUNTERMODE_UP;
htim1.Init.Period = 1000-1;
htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
htim1.Init.RepetitionCounter = 0;
htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
if (HAL_TIM_Base_Init(&htim1) != HAL_OK)
{
Error_Handler();
}
sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
if (HAL_TIM_ConfigClockSource(&htim1, &sClockSourceConfig) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim1, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN TIM1_Init 2 */
/* USER CODE END TIM1_Init 2 */
}
void HAL_TIM_Base_MspInit(TIM_HandleTypeDef* tim_baseHandle)
{
if(tim_baseHandle->Instance==TIM1)
{
/* USER CODE BEGIN TIM1_MspInit 0 */
/* USER CODE END TIM1_MspInit 0 */
/* TIM1 clock enable */
__HAL_RCC_TIM1_CLK_ENABLE();
/* TIM1 interrupt Init */
HAL_NVIC_SetPriority(TIM1_UP_TIM10_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(TIM1_UP_TIM10_IRQn);
/* USER CODE BEGIN TIM1_MspInit 1 */
/* USER CODE END TIM1_MspInit 1 */
}
}
void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef* tim_baseHandle)
{
if(tim_baseHandle->Instance==TIM1)
{
/* USER CODE BEGIN TIM1_MspDeInit 0 */
/* USER CODE END TIM1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_TIM1_CLK_DISABLE();
/* TIM1 interrupt Deinit */
HAL_NVIC_DisableIRQ(TIM1_UP_TIM10_IRQn);
/* USER CODE BEGIN TIM1_MspDeInit 1 */
/* USER CODE END TIM1_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
#include "stdio.h"
#include "button.h"
int timeCount = 0;
int timeCount_1ms = 0;
SystemButtonObj sys_btn_obj;
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim){
if(htim->Instance == TIM1){
timeCount++;
timeCount_1ms++;
if ((timeCount_1ms % 10) == 0) { //10ms
timeCount_1ms = 0;
GPIO_PinState PinState = HAL_GPIO_ReadPin(KEY_GPIO_Port, KEY_Pin); //down isr
if ((PinState == false) && (sys_btn_obj.flag == false)) {
sys_btn_obj.flag = true;
}
button_handler(&sys_btn_obj, PinState);
}
if(timeCount == 1000){
timeCount = 0;
//printf("time + 1s\n");
}
}
}
/* USER CODE END 1 */
3、在根目录创建button文件夹,分别有button.c、button.h文件组成。
1)、button.c文件
#include<stdbool.h>
#include "button.h"
void button_handler(SystemButtonObj *btn_obj, uint8_t press_state)
{
//printf("btn_obj->flag:%d\r\n", btn_obj->flag);
if (btn_obj->flag == false) {
return;
}
if (press_state == BUTTON_RELEASE) { //释放按键
if ((btn_obj->dow_counter != 0) && (btn_obj->long_press == 1)) {
btn_obj->long_press = 0;
btn_obj->dow_counter = 0;
return;
}
if (btn_obj->long_press == 1) {
btn_obj->flag = false;
return;
}
if (btn_obj->dow_counter > 2) {
btn_obj->click_cnt++;
//printf(" btn_obj->click_cnt %d, SHORT_PRESS_RELEASE_CNT %d LONG_PRESS_TRIGGER_TIME %d \r\n", btn_obj->click_cnt, SHORT_PRESS_RELEASE_CNT, LONG_PRESS_TRIGGER_TIME);
}
if (btn_obj->click_cnt) {
btn_obj->up_counter++;
if (btn_obj->up_counter > DOUBLE_PRESS_RELEASE_CNT) {
//printf(" btn_obj->up_counter %d SHORT_PRESS_RELEASE_CNT %d\r\n", btn_obj->up_counter, SHORT_PRESS_RELEASE_CNT);
if (btn_obj->click_cnt == 1) {
printf("counter %d, short \r\n", btn_obj->up_counter);
} else if (btn_obj->click_cnt == 2) {
printf("counter %d, double \r\n", btn_obj->up_counter);
} else {
printf("counter %d, multihit \r\n", btn_obj->up_counter);
}
btn_obj->click_cnt = 0;
btn_obj->up_counter = 0;
btn_obj->flag = false;
}
}
btn_obj->dow_counter = 0; //清除计数变量
}
if (press_state == btn_obj->press_status) { //低电平有效
//printf(" hahahaha press_state %d \r\n", press_state);
btn_obj->dow_counter++; //计算次数
//printf("counter %d, press_state:%d\r\n", btn_obj->dow_counter, press_state);
// 不松手的长按
if ((btn_obj->dow_counter > LONG_PRESS_TRIGGER_TIME) && (btn_obj->long_press == 0)) {
btn_obj->long_press = 1;
sys_btn_obj.press_event = ET_LONG_PRESS_EVENT;
printf("long press\r\n");
}
if (btn_obj->dow_counter > RESTART_TRIGGER_TIME) { //超长时间,重启事件
printf("restart press\r\n");
sys_btn_obj.press_event = ET_RESTART_PRESS_EVENT;
}
}
}
void key_event_handler(void)
{
switch (sys_btn_obj.press_event)
{
case ET_IDLE_PRESS_EVENT:
// printf("ET_IDLE_PRESS_EVENT\r\n");
break;
case ET_SHORT_PRESS_EVENT:
printf("ET_SHORT_PRESS_EVENT\r\n");
sys_btn_obj.press_event = ET_IDLE_PRESS_EVENT;
break;
case ET_DOUBLE_PRESS_EVENT:
printf("ET_DOUBLE_PRESS_EVENT\r\n");
sys_btn_obj.press_event = ET_IDLE_PRESS_EVENT;
break;
case ET_LONG_PRESS_EVENT:
printf("ET_LONG_PRESS_EVENT\r\n");
sys_btn_obj.press_event = ET_IDLE_PRESS_EVENT;
break;
case ET_RESTART_PRESS_EVENT:
printf("ET_RESTART_PRESS_EVENT\r\n");
sys_btn_obj.press_event = ET_IDLE_PRESS_EVENT;
break;
default :
break;
}
}
2)、button.h文件
#ifndef __BUTTON_H__
#define __BUTTON_H__
#ifdef __cplusplus
extern "C" {
#endif
#define BUTTON_TIMER_INTERVAL (50)
#define LONG_PRESS_TRIGGER_TIME (1500 / BUTTON_TIMER_INTERVAL)
#define RESTART_TRIGGER_TIME ((8 * 1000) / BUTTON_TIMER_INTERVAL)
//#define SHORT_PRESS_RELEASE_CNT (200 / BUTTON_TIMER_INTERVAL)
#define DOUBLE_PRESS_RELEASE_CNT (400 / BUTTON_TIMER_INTERVAL)
enum {
BUTTON_PRESS = 0,
BUTTON_RELEASE = 1,
};
typedef enum {
ET_IDLE_PRESS_EVENT,
ET_SHORT_PRESS_EVENT,
ET_DOUBLE_PRESS_EVENT,
ET_LONG_PRESS_EVENT,
ET_RESTART_PRESS_EVENT,
}BTN_EVENT_TYPE;
typedef struct {
uint8_t flag:1;
uint8_t press_status:1;
uint8_t long_press:1;
uint8_t double_press:1;
uint8_t click_cnt;
uint8_t up_counter;
uint8_t dow_counter;
BTN_EVENT_TYPE press_event;
} SystemButtonObj;
extern SystemButtonObj sys_btn_obj;
void button_handler(SystemButtonObj *btn_obj, uint8_t press_state);
void key_event_handler(void);
#ifdef __cplusplus
}
#endif
#endif
3)、main.c文件
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2023 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "iwdg.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "button.h"
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_USART1_UART_Init();
MX_TIM1_Init();
// MX_IWDG_Init();
/* USER CODE BEGIN 2 */
HAL_TIM_Base_Start_IT(&htim1);
printf("heihei button \r\n");
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
key_event_handler();
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
/** Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2);
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI|RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.LSIState = RCC_LSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 25;
RCC_OscInitStruct.PLL.PLLN = 168;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 4;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
Error_Handler();
}
}
/* USER CODE BEGIN 4 */
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
注意:keil上需要勾选Use MicroLIB,否则CubeMX生成的串口工程无法打印问题
四、运行结果
五、总结
好了,终于介绍完毕,以后裸机开发,有了按键框架方便很多,可移植到C51或者资源更少的芯片上,感谢参阅 ^_^。