keil5 STM32F103ZET6 l9110风扇模块 按键按下一次启动风扇,按下两次关闭风扇
时间: 2023-11-21 21:05:20 浏览: 110
ADC.rar_STM32F103ZET6 ADC_red bull_stm32f103zet6_红牛
你可以通过如下代码实现该功能:
```c
#include "stm32f10x.h"
// 定义风扇控制引脚和按键引脚
#define FAN_PIN GPIO_Pin_0
#define FAN_PORT GPIOB
#define KEY_PIN GPIO_Pin_1
#define KEY_PORT GPIOB
// 定义按键状态
#define KEY_IDLE 0
#define KEY_PRESS 1
#define KEY_RELEASE 2
// 定义按键变量和风扇状态变量
volatile uint8_t key_state = KEY_IDLE;
volatile uint8_t fan_state = 0;
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
// 配置风扇控制引脚为推挽输出
GPIO_InitStructure.GPIO_Pin = FAN_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(FAN_PORT, &GPIO_InitStructure);
// 配置按键引脚为上拉输入
GPIO_InitStructure.GPIO_Pin = KEY_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(KEY_PORT, &GPIO_InitStructure);
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
// 配置TIM2为10ms一次中断
TIM_TimeBaseStructure.TIM_Period = 999;
TIM_TimeBaseStructure.TIM_Prescaler = 7199;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// 配置TIM2中断优先级
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM2, ENABLE);
}
void TIM2_IRQHandler(void)
{
if(TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)
{
// 读取按键状态
uint8_t key = GPIO_ReadInputDataBit(KEY_PORT, KEY_PIN);
if(key_state == KEY_IDLE && key == 0)
{
key_state = KEY_PRESS;
}
else if(key_state == KEY_PRESS)
{
key_state = KEY_RELEASE;
}
else if(key_state == KEY_RELEASE && key == 1)
{
key_state = KEY_IDLE;
if(fan_state == 0)
{
fan_state = 1;
GPIO_SetBits(FAN_PORT, FAN_PIN);
}
else
{
fan_state = 0;
GPIO_ResetBits(FAN_PORT, FAN_PIN);
}
}
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
int main(void)
{
GPIO_Configuration();
TIM_Configuration();
while(1)
{
}
}
```
在程序中,我们使用了一个定时器TIM2来定时检测按键状态,并控制风扇的开关。在TIM2的中断处理函数中,通过检测按键的状态,来判断用户是否按下了按键。当按键被按下时,我们需要判断风扇的状态,如果风扇处于关闭状态,则将风扇打开,否则将风扇关闭。
需要注意的是,由于按键可能会产生抖动,因此我们需要在程序中加入合适的去抖动处理。在本示例中,我们在TIM2的中断处理函数中使用一个状态机来处理按键的状态,从而实现了去抖动。
阅读全文