超声波程序
#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
uchar flag0 = 0; //单片机发出10个脉冲标志位
uchar flag1 ; //测量标志位
long time; //记录定时器1时间
long distance = 0;//测得距离
code char tab[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90}; //数码管显示0~9段选位
void SendSupersonic();
void display();
void dalay(uchar k);
void main()
{
EA = 1;
ET0 = 0;
ET1 = 0;
TMOD = 0x12; //定时器1方式1,定时器0工作在方式2;定时器0用于输出40KHZ的脉冲信号;定时器1用于记录超声波来回时间
TH0 = 0xF4;
TL0 = 0xF4;
IT0 = 1; //外部中断0电平触发方式,低电平引起中断
EX0 = 0; //外部中断0允许位
P0 = 0x00;
while(1)
{
flag1 = 0;
TH1 = 0x00;
TL1 = 0x00;
SendSupersonic();
while(!flag1);
display();
}
}
void timer_0(void) interrupt 1 //40KHZ脉冲
{
flag2 = (~flag2);
flag0++;
}
void intsvr0(void) interrupt 0
{
TR1 = 0;
EX1 = 0;
time = TL1;
time += (long)TH1*256;
flag1 = 1;
}
void SendSupersonic()
{
TR0 = 1;
ET0 = 1; //打开定时器0开始发送40KHZ脉冲信号
ET1 = 1;
TR1 = 1; //打开定时器1,开始计时
while(flag0 < 18) ; //等待发送完10个脉冲信号
flag0 = 0;
ET0 = 0;
TR0 = 0;
}
void display()
{
distance = time*170;
distance = distance/1000000;
P2 = 0x7f;
P0 = tab[distance/10];
dalay(1);
P2 = 0xbf;
P0 = (tab[distance/1])&0x80;
dalay(1);
P2 = 0xdf;
P0 = tab[(distance*10)/10];
dalay(1);
P2 = 0xef;
P0 = tab[(((distance*100)%100)%10)/1];
dalay(1);
}
void dalay(uchar k)
{
uchar i,j;
for(i = 0;i <= k;i ++)
for(j = 0; j <= 110;j ++)
{
;
}
}
此帖出自
小平头技术问答
一周热门 更多>