stm32f4的库函数的红外遥控hx1838程序
时间: 2024-06-09 18:10:35 浏览: 163
以下是使用STM32F4库函数控制HX1838红外遥控的程序,其中使用PA0引脚连接到HX1838的OUT引脚,使用TIM3定时器捕获PA0引脚的信号来解码HX1838发送的红外信号。
```c
#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_tim.h"
#include "stm32f4xx_rcc.h"
uint16_t capture = 0;
uint16_t pulse_width = 0;
void TIM3_IRQHandler(void){
if(TIM_GetITStatus(TIM3, TIM_IT_CC1) == SET){
TIM_ClearITPendingBit(TIM3, TIM_IT_CC1);
if(capture == 0){
capture = 1;
pulse_width = TIM_GetCapture1(TIM3);
TIM_SetCounter(TIM3, 0);
}
else if(capture == 1){
capture = 0;
pulse_width = TIM_GetCapture1(TIM3) - pulse_width;
if(pulse_width > 1000){
//解码红外信号,执行相应操作
//根据实际情况进行操作,此处略去
}
}
}
}
void HX1838_Init(void){
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_ICInitTypeDef TIM_ICInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource0, GPIO_AF_TIM3);
TIM_TimeBaseStructure.TIM_Period = 0xFFFF;
TIM_TimeBaseStructure.TIM_Prescaler = 84-1;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
TIM_ICInitStructure.TIM_Channel = TIM_Channel_1;
TIM_ICInitStructure.TIM_ICPolarity = TIM_ICPolarity_Rising;
TIM_ICInitStructure.TIM_ICSelection = TIM_ICSelection_DirectTI;
TIM_ICInitStructure.TIM_ICPrescaler = TIM_ICPSC_DIV1;
TIM_ICInitStructure.TIM_ICFilter = 0x0F;
TIM_ICInit(TIM3, &TIM_ICInitStructure);
TIM_ITConfig(TIM3, TIM_IT_CC1, ENABLE);
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_Cmd(TIM3, ENABLE);
}
int main(void){
HX1838_Init();
while(1);
return 0;
}
```
在程序中,使用TIM3定时器捕获PA0引脚的信号,当捕获到上升沿时,如果capture等于0,则表示开始捕获,记录当前计数器值并将capture置为1;如果capture等于1,则表示捕获结束,记录捕获宽度并将capture置为0,然后进行红外信号解码并执行相应操作。
在HX1838_Init()函数中,首先使能GPIOA和TIM3的时钟,然后配置PA0引脚为复用功能,将其连接到TIM3的通道1上,并配置TIM3定时器的时钟分频、计数模式、计数器周期等参数。接着,配置TIM3的通道1为输入捕获模式,捕获上升沿,不分频,滤波器系数为0x0F。最后,使能TIM3的捕获比较1中断,并配置TIM3中断优先级,并启动TIM3定时器。
在main()函数中,调用HX1838_Init()函数进行初始化,并进入死循环等待中断发生。
阅读全文