超声波模块trig连P0^1 ,echo连P0^0 ,舵机的pwm输入连 P0^3。
已经有了一个程序 但实现不出效果 。。
求大神分享一下相关程序 或者帮忙修改一下程序 不胜感激
#include"reg52.h"
#define uint unsigned int
#define uchar unsigned char
sbit trig=P0^1;
sbit echo=P0^0;
sbit pwm=P0^3;
bit flag;
float distance;
uchar count;
uchar jd;
uint time,timeH,timeL;
void delayms(uint x)
{
uint i,j;
for(i=x;i>0;i--)
for(j=110;j>0;j--);
}
void delay20us()
{
uint i;
for(i=0;i<4;i++);
}
void duoji(uchar x)
{
jd=x;
count=0;
EA=1;
ET1=1;
TH1=0xfe;
TL1=0x33; //0.5ms
TR1=1;
}
void main()
{
TMOD=0x11;
while(1)
{
EA=0;
trig=1;
delay20us();
trig=0;
while(echo==0);
flag=0;
EA=1;
EX0=1;
TH0=0;
TL0=0;
TF0=0;
TR0=1;
delayms(20);
TR1=0;
if(flag==1)
{
time=timeH*256+timeL;
distance=1.085*time*0.017;
if(distance<10)
{
duoji(2);
delayms(5000);
duoji(3);
delayms(5000);
duoji(4);
delayms(5000);
duoji(3);
}
}
if(flag==0)
{
distance=0;
}
}
}
void exter() interrupt 0
{
timeH=TH0;
timeL=TL0;
flag=1;
EX0=0;
}
void t0() interrupt 1
{
TH0=0;
TL0=0;
}
void t1() interrupt 3
{
TH1=0xfe;
TL1=0x33;
if(count<jd) //判断0.5ms次数是否小于角度标识
pwm=1; //确实小于,PWM输出高电平
else
pwm=0; //大于则输出低电平
count=(count+1); //0.5ms次数加1
count=count%40; //次数始终保持为40 即保持周期为20m
}
|