**通过hc05蓝牙模块来控制小车的前进方向和避障功能,程序编译0错误0警告,但是烧录到51上面用spp蓝牙串口发送数据小车没有反应
**
程序如下
#include<reg51.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit IN1=P2^4;
sbit IN2=P2^3;
sbit IN3=P2^2;
sbit IN4=P2^1;
sbit ENA=P2^5;
sbit ENB=P2^0;
sbit Echo = P0^6;
sbit Trig = P0^7;
sbit DJ = P0^5;
uint stime = 0;
uint timer = 0;
uint S = 0;
uchar flag =0;
uchar PWMA,PWMB;
uint counter;
uchar i,j;
uchar jiaodu;
void delayms(uint ms)
{
uint msi,msj;
for(msi = 0;msi < ms;msi++)
for(msj = 0;msj < 112;msj++);
}
void stop()
{
IN1=0;
IN2=0;
IN3=0;
IN4=0;
}
void turnleft()
{
IN1=1;
IN2=0;
PWMA = 25;
IN3=1;
IN4=0;
PWMB = 25;
}
void turnright()
{
IN1=0;
IN2=1;
PWMA = 25;
IN3=0;
IN4=1;
PWMB = 25;
}
void back()
{
IN1=1;
IN2=0;
PWMA = 25;
IN3=0;
IN4=1;
PWMB = 25;
}
void straight()
{
IN1=0;
IN2=1;
PWMA = 25;
IN3=1;
IN4=0;
PWMB = 25;
}
void timer_init(){
TMOD|=0x11;
TH0=0;
TL0=0;
TH1=0xFE;
TL1=0x33;
ET0=1;
ET1=1;
TR1=1;
EA=1;
jiaodu=3;
}
void hcsr04()
{
Trig=1;
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
Trig=0;
while(!Echo);
TR0=1;
while(Echo);
TR0=0;
}
void distance(void)
{
stime=TH0*256+TL0;
TH0=0;
TL0=0;
S=(stime*1.8)/100;
}
void compare_distance()
{
if(jiaodu ==3 && S >= 15)
{
straight();
hcsr04();
distance();
}
else if(jiaodu ==3 && S < 15)
{
stop();
jiaodu = 2;
delayms(200);
hcsr04();
distance();
}
if(jiaodu == 2 && S >=15)
{
turnright();
delayms(500);
jiaodu =3;
delayms(200);
hcsr04();
distance();
}
else if(jiaodu == 2 && S < 15)
{
jiaodu = 4;
delayms(200);
hcsr04();
distance();
}
if(jiaodu == 4 && S >=15)
{
turnleft();
delayms(500);
jiaodu =3;
delayms(200);
hcsr04();
distance();
}
else if(jiaodu == 4 && S <15)
{
jiaodu =3;
delayms(200);
hcsr04();
distance();
}
}
void run(){
hcsr04();
distance();
compare_distance();
}
void Tmr1_isr() interrupt 3
{
TH1=0xFE;
TL1=0x33;
i++;
j++;
counter++;
if(counter <= jiaodu) DJ = 1;
if(counter > jiaodu && counter <= 40) DJ = 0;
if(counter > 40) counter = 0;
if(i < PWMA)
{
ENA = 1;
}
else
{
ENA = 0;
if(i >= 100)
{
i = 0;
}
}
if(j < PWMB)
{
ENB = 1;
}
else
{
ENB = 0;
if(j >= 100)
{
j = 0;
}
}
}
void Tmr0_isr() interrupt 1
{
flag=1;
}
void usartinit()
{
SCON=0X50;
TMOD=0X20;
PCON=0X80;
TH1=0XFA;
TL1=0XFA;
ES=1;
EA=1;
TR1=1;
ET1 = 0;
}
void main()
{
usartinit();
timer_init();
while(1);
}
void usart()interrupt 4
{
uchar res;
if(RI==1)
{
RI=0;
IN1=0;
IN2=0;
IN3=0;
IN4=0;
res=SBUF;
switch(res)
{
case('1'):turnleft();
break;
case('2'):turnright();
break;
case('3'):back();
break;
case('4'):straight();
break;
case('5'):run();
break;
case('0'):stop();
break;
}
}
}