STM32HAL-最简单的长、短、多击按键框架

server/2024/12/23 8:52:04/

目录

 概述 

一、开发环境

二、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 printfset 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) {    //10mstimeCount_1ms = 0;GPIO_PinState PinState = HAL_GPIO_ReadPin(KEY_GPIO_Port, KEY_Pin);	//down isrif ((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或者资源更少的芯片上,感谢参阅 ^_^。


http://www.ppmy.cn/server/46855.html

相关文章

Redis面试题深度解析

1、我看你做的项目中&#xff0c;都用到了redis&#xff0c;你在最近的项目中哪些场景使用了redis呢? 2、缓存穿透 布隆过滤器的误判现象 Redisson和Guava都对布隆过滤器进行了实现 3、缓存击穿 互斥锁&#xff0c;就是一个线程来修改&#xff0c;并占据了锁&#xff0c;另外其…

追寻美的指引--纪念西蒙斯

周六早上醒来&#xff0c;James Simons&#xff08;西蒙斯&#xff09;辞世的消息刷屏了。多数人知道他&#xff0c;是因为他的财富和量化对冲基金公司-文艺复兴。但他更值得为人纪念的身份&#xff0c;则是数学家和慈善家。 西蒙斯1938年生于麻省&#xff0c;毕业于MIT&#…

HarmonyOS 鸿蒙DevEco:导入无法运行提示Sync failed

场景&#xff1a;导入官网下载的案例后导入发现无法运行模拟机&#xff0c;Notifications提示Sync failed... 解决&#xff1a;查看Cause发现是版本问题&#xff0c;通过修改相关内容来解决该问题 1、打开案例地址找到hvigor文件夹 2、打开hvigor-config.json5&#xff0c;将&…

2023年全国职业院校技能大赛(高职组)“云计算应用”赛项赛卷7(私有云)

#需要资源&#xff08;软件包及镜像&#xff09;或有问题的&#xff0c;可私聊博主&#xff01;&#xff01;&#xff01; #需要资源&#xff08;软件包及镜像&#xff09;或有问题的&#xff0c;可私聊博主&#xff01;&#xff01;&#xff01; #需要资源&#xff08;软件包…

react自用小技巧(持续更新中)

react自用小技巧&#xff08;持续更新中&#xff09; 作者&#xff1a;devwolf 导言&#xff1a; 笔者应届时&#xff0c;投vue2就任一家大食品厂的资讯部后转成了react&#xff0c;写了一年出头的react类组件。然后跳槽到苏州科技城的一个原做影视渲染的公司开始全面转hook…

鸿蒙Ability Kit(程序框架服务)【UIAbility组件概述】

UIAbility组件概述 概述 UIAbility组件是一种包含UI的应用组件&#xff0c;主要用于和用户交互。 UIAbility的设计理念&#xff1a; 原生支持应用组件级的跨端迁移和多端协同。支持多设备和多窗口形态。 UIAbility划分原则与建议&#xff1a; UIAbility组件是系统调度的基…

OpenAI 推出ChatGPT Edu,为高校定制版本

近日&#xff0c;OpenAI 宣布推出 ChatGPT Edu&#xff0c;这是一款专为高校打造的 ChatGPT 版本&#xff0c;旨在帮助学生、教师、研究人员和校园运营部门以负责任的方式部署和使用 AI。 ChatGPT Edu 由 GPT-4o 提供支持&#xff0c;具备强大的文本和图像推理能力&#xff0c;…

大数据组件doc

1.flink Apache Flink Documentation | Apache Flink 2.kafka Apache Kafka 3.hbase Apache HBase ™ Reference Guide 4.zookeeper ZooKeeper: Because Coordinating Distributed Systems is a Zoo 5.spark Overview - Spark 3.5.1 Documentation 6.idea组件&#xff08;…