写一个STM32F407VET6按键中断控制RGB灯,短按亮灯,长按熄灭
时间: 2024-04-26 20:15:34 浏览: 13
灯。
#include "stm32f4xx.h"
#define LED_RED GPIO_Pin_0
#define LED_GREEN GPIO_Pin_1
#define LED_BLUE GPIO_Pin_2
#define KEY GPIO_Pin_13
uint32_t tick_count = 0;
uint8_t is_long_press = 0;
void LED_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_RED | LED_GREEN | LED_BLUE;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_SetBits(GPIOA, LED_RED | LED_GREEN | LED_BLUE);
}
void KEY_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
GPIO_InitStructure.GPIO_Pin = KEY;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOC, &GPIO_InitStructure);
SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOC, EXTI_PinSource13);
EXTI_InitStructure.EXTI_Line = EXTI_Line13;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling;
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
NVIC_InitStructure.NVIC_IRQChannel = EXTI15_10_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0x00;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0x01;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void delay_ms(uint32_t n)
{
tick_count = 0;
while (tick_count < n);
}
void EXTI15_10_IRQHandler(void)
{
if (EXTI_GetITStatus(EXTI_Line13) != RESET)
{
if (GPIO_ReadInputDataBit(GPIOC, KEY) == RESET)
{
is_long_press = 0;
delay_ms(100);
if (GPIO_ReadInputDataBit(GPIOC, KEY) == RESET)
{
GPIO_ResetBits(GPIOA, LED_RED | LED_GREEN | LED_BLUE);
is_long_press = 1;
}
}
else
{
if (is_long_press == 0)
{
GPIO_SetBits(GPIOA, LED_RED | LED_GREEN | LED_BLUE);
}
is_long_press = 0;
}
EXTI_ClearITPendingBit(EXTI_Line13);
}
}
int main(void)
{
SysTick_Config(SystemCoreClock / 1000);
LED_Init();
KEY_Init();
while (1)
{
}
}
void SysTick_Handler(void)
{
tick_count++;
}