stm单片机红外编码程序
以下是初始化配置函数,和红外发射函数,
使用的单片机为stm8s103,没有使用外部晶振,若用其他的单片机或晶振,在发送函数中的软件延时,还要通过示波器来调试。
还有一个问题,就是关于编译器的优化,这东西在时序要求很高的时候,尽量采用一些方式,把优化关掉,否则,软件延时很可能会有误差,从而造成通讯的问题。
void init()
{
//时钟配置
CLK_SYSCLKConfig(CLK_PRESCALER_HSIDIV1);//内部高速RC振荡时钟分频
CLK_SYSCLKConfig(CLK_PRESCALER_CPUDIV1);//CPU核心时钟分频
//IO配置
//可不用设置,在开启相应外设时,外设会接管io
//TIM配置
asm("sim"); // 关全局中断
TIM2->PSCR = 0x00;
TIM2->ARRH = (u8)(418 >> 8);
TIM2->ARRL = (u8)(418);
TIM2->CCMR1 = 0x60;
TIM2->CCER1 = 0x01;
TIM2->CCMR1 |= 0x08;
TIM2->CCR1H = 0;
TIM2->CCR1L = 100;
TIM2_OC1PreloadConfig(ENABLE);
TIM2->CCMR2 = 0x60;
TIM2->CCER1 |= 0x10;
TIM2->CCMR2 |= 0x08;
TIM2->CCR2H = 1;
TIM2->CCR2L = 0;
TIM2->CCMR3 = 0x60;
TIM2->CCER2 |= 0x01;
TIM2->CCMR3 |= 0x08;
TIM2->CCR3H = 1;
TIM2->CCR3L = 0;
TIM2->CR1 |= 0x81;
GPIOD->DDR &= ~(1<<5);
GPIOD->CR1 |= (1<<5);
GPIOD->ODR |= (1<<5);
GPIOD->DDR &= ~(1<<6);
GPIOD->CR1 |= (1<<6);
GPIOD->ODR |= (1<<6);
GPIO_Init(GPIOD, GPIO_PIN_3, GPIO_MODE_OUT_PP_LOW_FAST);
UART1->BRR2 = 0x02; // 设置波特率9600
UART1->BRR1 = 0x68; // 8M/9600 = 0x341
UART1->CR2 = 0x2C; // 允许接收中断,允许接收,允许发送
UART1->CR1 &=~ (1 << 5); //使能uart1
GPIO_DeInit(GPIOB);
asm("rim"); // 开全局中断
}
#pragma optimize=none
void IR_send(u8 add_l,u8 add_h,u8 dat)
{
u8 t,temp;
temp =~ dat;
//发送前导码
IR_1;
IR_delay(4350);
IR_0;
IR_delay(2200);
for(t = 0; t < 8; t++) //发送低8位地址
{
if(add_l&0x01)
{
IR_1;
IR_delay(300);
IR_0;
IR_delay(800);
}
else
{
IR_1;
IR_delay(270);
IR_0;
IR_delay(270);
}
add_l >>= 1;
}
for(t = 0; t < 8; t++) //发送高8位地址
{
if(add_h&0x01)
{
IR_1;
IR_delay(300);
IR_0;
IR_delay(800);
}
else
{
IR_1;
IR_delay(270);
IR_0;
IR_delay(270);
}
add_h >>= 1;
}
for(t = 0; t < 8; t++) //发送8位数据
{
if(dat&0x01)
{
IR_1;
IR_delay(300);
IR_0;
IR_delay(800);
}
else
{
IR_1;
IR_delay(270);
IR_0;
IR_delay(270);
}
dat >>= 1;
}
for(t = 0; t < 8; t++) //发送8位数据反码
{
if(temp&0x01)
{
IR_1;
IR_delay(300);
IR_0;
IR_delay(800);
}
else
{
IR_1;
IR_delay(270);
IR_0;
IR_delay(270);
}
temp >>= 1;
}
IR_1;IR_delay(270);
IR_0;IR_delay(270);
}
评论