stm32 将LED灯分为a、b两组,当按键第一次按下时,a组LED灯熄灭,b组LED灯闪烁;当按键再次按下时,a组LED灯闪烁,b组LED灯熄灭,按键控制可如此反复。
时间: 2024-04-30 11:19:43 浏览: 55
stm32 按键和LED控制
可以使用STM32的GPIO控制LED灯的亮灭,使用外部中断控制按键的读取。可以按照以下步骤实现:
1. 初始化GPIO,将a组LED灯和b组LED灯的对应GPIO口设置为输出模式,初始状态为亮(高电平)。
2. 初始化外部中断,将按键对应的GPIO口设置为输入模式,开启外部中断并设置中断触发方式为下降沿触发。
3. 在中断服务函数中,判断按键状态。当按键第一次按下时,将a组LED灯熄灭,b组LED灯闪烁;当按键再次按下时,将a组LED灯闪烁,b组LED灯熄灭。
4. 在主函数中,使用循环不断进行LED灯亮灭的控制。
以下是示例代码,仅供参考:
```c
#include "stm32f10x.h"
void GPIO_Configuration(void);
void EXTI_Configuration(void);
void delay_ms(uint32_t nTime);
uint8_t led_a = 1, led_b = 1; // 初始化状态为亮
uint8_t button_state = 0; // 按键状态,0为未按下,1为第一次按下,2为再次按下
int main(void)
{
GPIO_Configuration();
EXTI_Configuration();
while (1)
{
if (button_state == 1)
{
GPIO_ResetBits(GPIOA, GPIO_Pin_0); // 熄灭a组LED灯
for (int i = 0; i < 5; i++)
{
GPIO_ResetBits(GPIOB, GPIO_Pin_0); // 闪烁b组LED灯
delay_ms(100);
GPIO_SetBits(GPIOB, GPIO_Pin_0);
delay_ms(100);
}
}
else if (button_state == 2)
{
for (int i = 0; i < 5; i++)
{
GPIO_ResetBits(GPIOA, GPIO_Pin_0); // 闪烁a组LED灯
delay_ms(100);
GPIO_SetBits(GPIOA, GPIO_Pin_0);
delay_ms(100);
}
GPIO_ResetBits(GPIOB, GPIO_Pin_0); // 熄灭b组LED灯
}
}
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_GPIOB, ENABLE);
// a组LED
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// b组LED
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOB, &GPIO_InitStructure);
// 按键
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
GPIO_Init(GPIOA, &GPIO_InitStructure);
}
void EXTI_Configuration(void)
{
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
// 按键中断线连接到GPIO口
GPIO_EXTILineConfig(GPIO_PortSourceGPIOA, GPIO_PinSource1);
EXTI_InitStructure.EXTI_Line = EXTI_Line1;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void EXTI1_IRQHandler(void)
{
if (EXTI_GetITStatus(EXTI_Line1) != RESET)
{
EXTI_ClearITPendingBit(EXTI_Line1);
// 延时去抖动
delay_ms(10);
if (button_state == 0)
{
led_a = 0;
led_b = 1;
button_state = 1;
}
else if (button_state == 1)
{
led_a = 1;
led_b = 0;
button_state = 2;
}
else if (button_state == 2)
{
led_a = 0;
led_b = 1;
button_state = 1;
}
}
}
void delay_ms(uint32_t nTime)
{
uint32_t TimingDelay = 0;
TimingDelay = nTime;
while(TimingDelay != 0)
{
TimingDelay--;
}
}
```
阅读全文