51用c语言怎么编程检测US-100超声波测距模块echo/rx引脚输出高电平时间长度,,谁能给我个模板
1个回答
推荐于2016-07-24 · 知道合伙人互联网行家
关注
展开全部
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
unsigned char code smg[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,0x00};
sbit tr=P1^0;
sbit ec=P1^1;
uint distance,time,tl,th;
void delay_20us(void )
{
uchar a ;
for(a=0;a<100;a++);
}
void delay(uint a )
{
while(a--);
}
void display(void )
{
P2=0xff;
P2=0xfe;
P0=smg[distance/100];
delay(200);
P2=0xff;
P2=0xfd;
P0=smg[distance%100/10];
delay(200);
P2=0xff;
P2=0xfb;
P0=smg[distance%10];
delay(200);
}
void main(void )
{
uchar i;
TMOD=0X10;
while(1)
{
tr=1; //超声波输入端
delay_20us(); //延时20us
tr=0; //产生一个20us的脉冲
while(ec==0); //等待Echo回波引脚变高电平
TH1=0; //定时器1清零
TL1=0; //定时器1清零
TF1=0; //计数溢出标志
TR1=1; //启动定时器1
while(ec==1);
th=TH1;
tl=TL1;
TL1=0;
TH1=0;
TR1=0; //关闭定时器1
time=th*256+tl;
distance=time*0.017; //厘米 */
display();
}
}
#define uchar unsigned char
#define uint unsigned int
unsigned char code smg[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e,0x00};
sbit tr=P1^0;
sbit ec=P1^1;
uint distance,time,tl,th;
void delay_20us(void )
{
uchar a ;
for(a=0;a<100;a++);
}
void delay(uint a )
{
while(a--);
}
void display(void )
{
P2=0xff;
P2=0xfe;
P0=smg[distance/100];
delay(200);
P2=0xff;
P2=0xfd;
P0=smg[distance%100/10];
delay(200);
P2=0xff;
P2=0xfb;
P0=smg[distance%10];
delay(200);
}
void main(void )
{
uchar i;
TMOD=0X10;
while(1)
{
tr=1; //超声波输入端
delay_20us(); //延时20us
tr=0; //产生一个20us的脉冲
while(ec==0); //等待Echo回波引脚变高电平
TH1=0; //定时器1清零
TL1=0; //定时器1清零
TF1=0; //计数溢出标志
TR1=1; //启动定时器1
while(ec==1);
th=TH1;
tl=TL1;
TL1=0;
TH1=0;
TR1=0; //关闭定时器1
time=th*256+tl;
distance=time*0.017; //厘米 */
display();
}
}
追问
谢谢
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询