stm單片機(jī)紅外編碼程序
以下是初始化配置函數(shù),和紅外發(fā)射函數(shù),
使用的單片機(jī)為stm8s103,沒(méi)有使用外部晶振,若用其他的單片機(jī)或晶振,在發(fā)送函數(shù)中的軟件延時(shí),還要通過(guò)示波器來(lái)調(diào)試。
還有一個(gè)問(wèn)題,就是關(guān)于編譯器的優(yōu)化,這東西在時(shí)序要求很高的時(shí)候,盡量采用一些方式,把優(yōu)化關(guān)掉,否則,軟件延時(shí)很可能會(huì)有誤差,從而造成通訊的問(wèn)題。
void init()
{
//時(shí)鐘配置
CLK_SYSCLKConfig(CLK_PRESCALER_HSIDIV1);//內(nèi)部高速RC振蕩時(shí)鐘分頻
CLK_SYSCLKConfig(CLK_PRESCALER_CPUDIV1);//CPU核心時(shí)鐘分頻
//IO配置
//可不用設(shè)置,在開(kāi)啟相應(yīng)外設(shè)時(shí),外設(shè)會(huì)接管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"); // 開(kāi)全局中斷
}
#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);
}
評(píng)論