#include
#include
#define uint unsigned int
#define uchar unsigned char
uchar code table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0xbf};
sbit P2_0=P2^0;
sbit P2_1=P2^1;
sbit P2_2=P2^2;
sbit trig=P1^2;//这个口是接led的口,没问题,换了口也一样
sbit echo=P1^3;
bit flag;
unsigned long m;;
void delay(uint i)
{
while(i--);
}
void Delay40ms() //@11.0592MHz
{
unsigned char i, j, k;
_nop_();
_nop_();
i = 2;
j = 175;
k = 75;
do
{
do
{
while (--k);
} while (--j);
} while (--i);
}
void Delay40us() //@11.0592MHz
{
unsigned char i;
i = 108;
while (--i);
}
void xianshi(unsigned long s)
{
uchar ge,shi,bai;
ge=s%100%10;
shi=s%100/10;
bai=s/100;
P0=table[bai];
P2_0=0;
delay(70);
P2_0=1;
P0=table[shi];
P2_1=0;
delay(70);
P2_1=1;
P0=table[ge];
P2_2=0;
delay(70);
P2_2=1;} //显示函数,测过给数能显示
void main()
{
TMOD=0x01;
TL0=0; //设置定时器0初值低8位
TH0=0; //设置定时器0初值高8位
TR0=0; //停止定时器0
ET0=1; //Timer0中断允许
EX0=0; //外部INT0中断关闭
EX1=0;
EA=1;
while(1)
{
trig=1;
Delay40us();
trig=0;
while(echo==0);
TH0=0;
flag=0;
TL0=0;
TR0=1;
while(echo==1);
TR0=0;
m=((TH0*256+TL0)*0.9521)/58;
if(m>400||flag==1)
{m=0;}
xianshi(m);
Delay40ms();
}}
void t0()interrupt 0
{
flag=1;
}
认为是while(echo==1),while(echo==0),这两个循环成了死循环所以不能显示,但不知道是为啥
http://www.doc88.com/p-679120731760.html
一点建议:51要读的端口先配置成1(虽然上电默认高电平,但是不保险) 超声供电一定要保证,不然没用。