STM32 BS8116a-3触摸按键例程
时间: 2023-12-09 15:04:43 浏览: 239
STM32触摸按键实验
以下是基于STM32和BS8116a-3的触摸按键的示例代码:
```c
#include "stm32f10x.h"
#include "bs8116a3.h"
#define KEY_SCAN_INTERVAL 50 //扫描按键的时间间隔ms
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
uint16_t keyValue = 0; //存储按键状态
void TIM2_IRQHandler(void)
{
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
//扫描按键状态
uint16_t newKeyValue = BS8116a3_Scan();
//如果按键状态发生变化
if (newKeyValue != keyValue)
{
keyValue = newKeyValue;
//根据按键状态控制LED灯的亮灭
if (keyValue & 0x01) //按键1按下
{
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
}
else //按键1未按下
{
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Disable;
}
TIM_OC1Init(TIM3, &TIM_OCInitStructure);
}
}
}
int main(void)
{
//配置GPIO口
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
//配置TIM3
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Period = 1000;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
//配置TIM3的输出比较通道1
TIM_OCStructInit(&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Disable;
TIM_OC1Init(TIM3, &TIM_OCInitStructure);
//配置BS8116a-3
BS8116a3_Init();
//配置TIM2用于定时扫描按键状态
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
TIM_TimeBaseStructure.TIM_Period = KEY_SCAN_INTERVAL;
TIM_TimeBaseStructure.TIM_Prescaler = SystemCoreClock / 1000 - 1;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM2, ENABLE);
//启用中断
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
while (1)
{
}
}
```
上述代码中,使用了STM32的定时器TIM2作为按键扫描定时器,定时周期为50ms。在TIM2的中断服务函数中,通过调用`BS8116a3_Scan()`函数扫描BS8116a-3的按键状态,并根据按键状态控制LED灯的亮灭。
为了方便起见,这里使用了STM32的定时器TIM3控制LED灯的亮灭。通过调整定时器的输出比较通道1的输出状态来控制LED灯的亮灭。
阅读全文