STM32 HAL库 按键中断实现单击/双击/长按(无阻塞)

STM32 HAL库 按键中断实现单击/双击/长按(无阻塞)

理论可以实现无限击,但没有使用场景。

理论可以实现无限按钮,当前仅一个。只需为按钮结构体加入编号,在处理函数中轮询即可。


准备

首先配置一个1ms定时器中断,也可以比1ms长或者短,该时长即是后面双击等待时间、长按时间、消抖时间的单位。

配置好按键GPIO,配置双边沿触发中断。


代码

复制button.c、button.h进入工程src、inc目录,并导入工程。

/******************   button.c  ******************/

# include "button.h"

// 状态机逻辑,按键中断处理
void BUTTON_EXTI_Callback(uint16_t GPIO_Pin,BUT* but)
{
	if(GPIO_Pin == but_Pin)
	{
		if(HAL_GPIO_ReadPin(but_GPIO_Port,but_Pin) == GPIO_PIN_RESET)
		{
			if((but->but_state & 0x01) == 0x00)
			{
				HAL_TIM_Base_Start_IT(but->tim);
				but->but_time = 0;
				but->but_state |= 0x05;
			}
			if((but->but_state & 0x1C) == 0x18)
			{
				but->but_state |= 0x04;
			}
		}
		else
		{
			if(((but->but_state & 0x18) == 0x18) && (but->wait_time < but->tap2_time))
			{
				but->but_state |= 0x80;
			}
		}
	}
}

// 状态机逻辑,定时器处理
void BUTTON_TIM_PeriodCallback(TIM_HandleTypeDef* htim,BUT* but)
{
	if(htim == but->tim)
	{
		if((but->but_state & 0x04) == 0x04)
		{
			++but->but_time;
			if(but->but_time >= but->debounce_time)
			{
				if(HAL_GPIO_ReadPin(but->BUT_GPIO_Port,but->BUT_Pin) == GPIO_PIN_RESET)
				{
					if((but->but_state & 0x10) == 0x10)
					{
						but->but_state |= 0x30;
						but->but_state = 0x00;
						but->KEY = 2;					
					}
					else
					{
						but->wait_time = 0;
						but->but_state = 0x19;
					}
				}
				else
				{
					but->wait_time = 0;
					but->but_state &= (!0x04);
				}
			}
		}
		if((but->but_state & 0x88) == 0x88)
		{
			++but->wait_time;
			if(but->wait_time >= but->tap2_time)
			{
				but->KEY = 1;
				but->but_state = 0x00;
			}
		}
		else if((but->but_state & 0x88) == 0x08)
		{
			++but->wait_time;
			if(but->wait_time >= but->longpress_time)
			{
				but->KEY = 3;
				but->but_state = 0x00;
			}
		}
	}
}
/******************   button.h   ******************/

#ifndef __BUTTON_H
#define __BUTTON_H

#include "main.h"

// 结构体定义
typedef struct but_struct
{
	// state BIT0:按下 BIT1:松开 BIT2:消抖 BIT3:等待 
    //       BIT4:点按一次 BIT5:点按两次 BIT6 等待双击/等待长按
	volatile uint8_t but_state; 
	uint16_t but_time;  			//消抖计数器
	uint16_t wait_time;				//等待计数器
	uint16_t debounce_time;   		//消抖时间(ms)
	uint16_t tap2_time;				//最长双击时间(ms)
	uint16_t longpress_time;		//最短长按时间(ms)
	uint8_t KEY;					//更新按键状态 0:无 1:单击 2:双击 3:长按
	GPIO_TypeDef* BUT_GPIO_Port; 	//按键GPIOPORT
	uint16_t BUT_Pin;				//按键GPIOPin
	TIM_HandleTypeDef* tim;			//按键事件处理定时器
}BUT;

void BUTTON_EXTI_Callback(uint16_t GPIO_Pin,BUT* but0);
void BUTTON_TIM_PeriodCallback(TIM_HandleTypeDef* htim,BUT* but0);

#endif

在主函数中include并定义结构体;

将BUTTON_EXTI_Callback(uint16_t GPIO_Pin,BUT* but0)  和  BUTTON_TIM_PeriodCallback(TIM_HandleTypeDef* htim,BUT* but0)两函数分别放入中断处理函数中,即可通过结构体中的KEY成员读取到按键状态,完成按键检测。

下为OLED显示按键状态的案例。使用F103c8t6作为主控

/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 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 "i2c.h"
#include "tim.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "oled.h"
#include "stdlib.h"
#include "stdio.h"
#include "math.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 */
BUT but = {
	.but_state = 0x00,
	.but_time = 0,
	.wait_time = 0,
	.BUT_GPIO_Port = but_GPIO_Port,
	.BUT_Pin = but_Pin,
	.debounce_time = 10,
	.longpress_time = 1000,
	.tap2_time = 500,
	.KEY = 0,
	.tim = &htim2,
};

/* 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_I2C1_Init();
  MX_TIM4_Init();
  MX_TIM2_Init();
  /* USER CODE BEGIN 2 */
	
	OLED_Init();                           //OLED初始
	OLED_Clear();                         //清屏
	OLED_ShowString(0,0,"KEY State:",16, 0);    //反相显示8X16字符串
	
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
		if(but.KEY == 1)
			OLED_ShowString(32,2,"TAP ONCE  ",12,0);//正相显示6X8字符串
		if(but.KEY == 2)
			OLED_ShowString(32,2,"TAP TWICE ",12,0);//正相显示6X8字符串
		if(but.KEY == 3)
			OLED_ShowString(32,2,"LONG PRESS",12,0);//正相显示6X8字符串
		

		HAL_Delay(100);
		
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  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 */

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
	BUTTON_EXTI_Callback(GPIO_Pin,&but);
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	BUTTON_TIM_PeriodCallback(htim,&but);
}

/* 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 */


效果如上

作者:F11sh

物联沃分享整理
物联沃-IOTWORD物联网 » STM32 HAL库 按键中断实现单击/双击/长按(无阻塞)

发表回复