stm32f407实现红外遥控2个按键分别控制一个led灯 代码
时间: 2023-10-22 22:07:54 浏览: 232
基于stm32红外控制代码
下面是使用STM32F407实现红外遥控2个按键分别控制一个LED灯的代码示例:
```c
#include "stm32f4xx.h"
void GPIO_Configuration(void);
void EXTI_Configuration(void);
void LED_On(uint16_t led);
void LED_Off(uint16_t led);
int main(void)
{
GPIO_Configuration();
EXTI_Configuration();
while (1)
{
// 循环执行其他任务
}
}
void GPIO_Configuration(void)
{
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOC, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
// 配置LED引脚为输出模式
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
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_100MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 配置按键引脚为输入模式
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13 | GPIO_Pin_14;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void EXTI_Configuration(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
EXTI_InitTypeDef EXTI_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
// 配置外部中断线路13,对应按键1
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; // 上升沿触发
EXTI_InitStructure.EXTI_LineCmd = ENABLE;
EXTI_Init(&EXTI_InitStructure);
// 配置外部中断线路14,对应按键2
SYSCFG_EXTILineConfig(EXTI_PortSourceGPIOC, EXTI_PinSource14);
EXTI_InitStructure.EXTI_Line = EXTI_Line14;
EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt;
EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising; // 上升沿触发
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 = 0x00;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}
void LED_On(uint16_t led)
{
GPIO_SetBits(GPIOA, led);
}
void LED_Off(uint16_t led)
{
GPIO_ResetBits(GPIOA, led);
}
// 外部中断处理函数
void EXTI15_10_IRQHandler(void)
{
if (EXTI_GetITStatus(EXTI_Line13) != RESET)
{
// 按键1中断触发处理
LED_On(GPIO_Pin_0);
EXTI_ClearITPendingBit(EXTI_Line13);
}
if (EXTI_GetITStatus(EXTI_Line14) != RESET)
{
// 按键2中断触发处理
LED_On(GPIO_Pin_1);
EXTI_ClearITPendingBit(EXTI_Line14);
}
}
```
以上代码假设红外遥控器的按键分别连接到STM32F407的PC13和PC14引脚,LED灯分别连接到STM32F407的PA0和PA1引脚。在代码中,我们配置了GPIO引脚、外部中断以及中断优先级,以实现按键触发对应LED灯的控制。请根据实际连接进行相应的修改和调整。
阅读全文