|
本帖最后由 Lyricalstyle 于 2013-3-31 16:03 编辑
#include<reg52.h>
#include<math.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
uint i=0,j,URTAReceivedCount=0,n=1,count=10;
uchar data Tempdatatable[2];
uchar jishu;
sbit pwm=P2^0;
uchar jd;
void delay(uchar i)
{
uchar j,k;
for(j=i;j>0;j--)
for(k=125;k>0;k--);
}
void Time0_Init() //定时器0开启,每0.5毫秒出发一次定时器0中断
0{
IE=0x82;
TH0=0xfe;
TL0=0x33;
TR0=1;
}
void Delay_1ms(uint i)
{
uchar x,j;
for(j=0;j<i;j++)
for(x=0;x<=148;x++);
}
void moto_forward() //控制电机
{
P0=0x0a;
Delay_1ms(200);
P0=0x00;
count--;
Tempdatatable[1]=0xff;
}
void moto_backward()
{
P0=0x05;
Delay_1ms(200);
P0=0x00;
count--;
Tempdatatable[1]=0xff;
}
void moto_left()
{
P0=0x08;
Delay_1ms(200);
P0=0x00;
count--;
Tempdatatable[1]=0xff;
}
void moto_right()
{
P0=0x02;
Delay_1ms(200);
P0=0x00;
count--;
Tempdatatable[1]=0xff;
}
void Time0_Int() interrupt 1 //定时0中断 控制舵机
{
TH0=0xfe;
TL0=0x33;
if(jishu<jd)
pwm=1;
else
pwm=0;
jishu=(jishu+1);
jishu=jishu%40;
}
void Com_Int(void) interrupt 4 //串口中断
{
uchar temp;
ES=0; //关串口中断
RI=0; //软件清除接收中断
temp=SBUF;
if(temp==0XFF && URTAReceivedCount<3)
{
Tempdatatable[0]==0XFF; //包头
URTAReceivedCount++;
}
else
{
Tempdatatable[n]=temp;
n++;
}
if(URTAReceivedCount==2)//包尾
{
Tempdatatable[0]=0XFF;
Tempdatatable[2]=0XFF;
n=1;
URTAReceivedCount=0; //组包完毕
temp="";
}
ES=1;//开串口中断
}
void main() //程序入口
{
jd=1;
jishu=0;
Time0_Init();
TMOD = 0x21; //允许定时器0和1
PCON = 0x80;
SCON = 0x50;
TH1 = 0xfA; //设置波特率 9600
TL1 = 0xfA;
TR1 = 1; //启动定时器1
ET1 =0;
ES = 1; //开串口中断
PS=1; //设计串行口中断优先级
EA = 1; //设计串行口中断优先级
IT0=0;
EX0=1;
while(1)
{
if(Tempdatatable[0]==0XFF && Tempdatatable[2]==0XFF)
{
switch(Tempdatatable[1])
{
case 0X02:
moto_forward();
break;
case 0x03:
moto_backward();
break;
case 0x04:
moto_left();
break;
case 0x05:
moto_right();
break;
case 0x06: //如果是wifi上位机发送的是ff06ff 舵机标志位加1
jd++;
break;
default : TR0=0;TR2=0;
break;
}
}
}
}
|
|