#include <REGX52.H>
#include <INTRINS.H>
#include "app/Timer0.h"
sbit left_lun_1 = P0^2;
sbit left_lun_2 = P0^3;
sbit right_lun_1 = P0^0;
sbit right_lun_2 = P0^1;
unsigned char SBUFs,DIAN_state;
void UART_init(){ //9600bps@11.0592MHz
SCON = 0x50;
PCON |= 0x80;
TMOD |= 0x20; //设置定时器模式
TL1 = 0xFA; //设定定时初值
TH1 = 0xFA; //设定定时初值
ES = 1; //开启接受
EA = 1;
ET1 = 0;
TR1 = 1; //定时器1开始计时
}
void main (){
UART_init(); //初始化定时器1
Timer0Init(); //初始化定时器0
left_lun_1 = 0;left_lun_2 = 0;right_lun_1 = 0;right_lun_2 = 0; //默认状态
while(1){
}
}
void Delay1000us() //@11.0592MHz
{
unsigned char i, j;
_nop_();
_nop_();
i = 200;
j = 105;
do
{
while (--j);
} while (--i);
}
void UART_Routine() interrupt 4
{
RI = 0;
//SBUF为接受到的信息
SBUFs = SBUF;
}
void Timer0_Routine() interrupt 1
{
static unsigned int T0Count;
TL0 = 0x18; //设置定时初值
TH0 = 0xFC; //设置定时初值
T0Count++;
if(T0Count >= 1000)T0Count = 0;
if(SBUFs == 0x00){
//停止
left_lun_1 = 0;left_lun_2 = 0;right_lun_1 = 0;right_lun_2 = 0;
DIAN_state = 0;
}
if(SBUFs == 0xFF){
//取消转弯
if(DIAN_state == 0) SBUFs = 0x00;
if(DIAN_state == 1) SBUFs = 0x01;
if(DIAN_state == 2) SBUFs = 0x02;
}
if(SBUFs == 0x01){
//前进
left_lun_1 = 0;left_lun_2 = 1;right_lun_1 = 0;right_lun_2 = 1;
DIAN_state = 1;
}
if(SBUFs == 0x02){
//后退
left_lun_1 = 1;left_lun_2 = 0;right_lun_1 = 1;right_lun_2 = 0;
DIAN_state = 2;
}
if(SBUFs == 0x03){
//转弯 左
right_lun_1 = 0;right_lun_2 = 1;
if(DIAN_state == 1){
if(T0Count >= 4){
T0Count = 0;
left_lun_1 = 0;left_lun_2 = 1;
}else{
left_lun_1 = 0;left_lun_2 = 0;
}
}else if(DIAN_state == 2){
if(T0Count >= 4){
T0Count = 0;
right_lun_1 = 1;right_lun_2 = 0;
}else{
right_lun_1 = 0;right_lun_2 = 0;
}
}
}
if(SBUFs == 0x04){
//转弯 右
left_lun_1 = 0;left_lun_2 = 1;
if(DIAN_state == 1){
if(T0Count >= 4){
T0Count = 0;
right_lun_1 = 0;right_lun_2 = 1;
}else{
right_lun_1 = 0;right_lun_2 = 0;
}
}else if(DIAN_state == 2){
if(T0Count >= 4){
T0Count = 0;
left_lun_1 = 1;left_lun_2 = 0;
}else{
left_lun_1 = 0;left_lun_2 = 0;
}
}
}
}
P0口接了四个电机,0-3接口接两个电机,另外两个共享电源
前面调用了定时器0的void