stm單片機紅外編碼程序
以下是初始化配置函數(shù),和紅外發(fā)射函數(shù),
使用的單片機為stm8s103,沒有使用外部晶振,若用其他的單片機或晶振,在發(fā)送函數(shù)中的軟件延時,還要通過示波器來調(diào)試。
還有一個問題,就是關(guān)于編譯器的優(yōu)化,這東西在時序要求很高的時候,盡量采用一些方式,把優(yōu)化關(guān)掉,否則,軟件延時很可能會有誤差,從而造成通訊的問題。
void init()
{
//時鐘配置
CLK_SYSCLKConfig(CLK_PRESCALER_HSIDIV1);//內(nèi)部高速RC振蕩時鐘分頻
CLK_SYSCLKConfig(CLK_PRESCALER_CPUDIV1);//CPU核心時鐘分頻
//IO配置
//可不用設(shè)置,在開啟相應(yīng)外設(shè)時,外設(shè)會接管io
//TIM配置
asm("sim"); // 關(guān)全局中斷
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; // 設(shè)置波特率9600
UART1->BRR1 = 0x68; // 8M/9600 = 0x341
UART1->CR2 = 0x2C; // 允許接收中斷,允許接收,允許發(fā)送
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;
//發(fā)送前導(dǎo)碼
IR_1;
IR_delay(4350);
IR_0;
IR_delay(2200);
for(t = 0; t < 8; t++) //發(fā)送低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++) //發(fā)送高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++) //發(fā)送8位數(shù)據(jù)
{
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++) //發(fā)送8位數(shù)據(jù)反碼
{
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);
}
評論