【超声波测距模块】-【机器人的耳朵】
#include<avr/io.h>
#include<avr/iom16.h>
#include<util/delay.h>
int main(void)
{
DDRA=0x00;
PORTA=0x00; //PA口初始化
DDRD=0xff;
PORTD=0xff; //PD口初始化
char j,i;
int h,u,l;
while(1)
{
j=1; //激活while(j)循环
i=1; //激活while(i)循环
u=6000; //还原检测循环
PORTA&=(1<<0); //PA0脚高电平
_delay_us(20); //延时20US
PORTA&=~(1<<0); //PA0脚低电平。发送20US的高电平脉冲
while(j)
{
if(PINA&(1<<1)) //判断PA1有无返回高电平
{
while(i)
{
h=0; //初始计数变量
_delay_us(10); //延时及计数
h=h+10; //计数累加10us
if(!(PINA&(1<<1))) //判断PA1口是否跳转到低电平
{
i=0; //至while值为零
j=0; //检测完成,跳出while(j)
l=h*3; //计算出mm
if(250>=l)
{
PORTD=0b00000001;
}
else if(500>=l&&l>=250)
{
PORTD=0b00000010;
}
else if(750>=l&&l>=500)
{
PORTD=0b00000100;
}
else if(1000>=l&&l>=750)
{
PORTD=0b00001000;
}
else if(1250>=l&&l>=1000)
{
PORTD=0b00010000;
}
else if(1500>=l&&l>=1250)
{
PORTD=0b00100000;
}
else if(1750>=l&&l>=1500)
{
PORTD=0b01000000;
}
else if(2000>=l&&l>=1750)
{
PORTD=0b10000000;
}
else
{
PORTD=0b00000000;
}
_delay_ms(600); //检测完成,延迟显示
}
}
}
_delay_us(10); //当PA1未返回高电平开始循环检测,间隔10us
u=u-1; //循环程序固定循环U次
if(u&0) //当循环U次后,判断U是否为0,跳出while(j)
{
j=0;
}
}
}
}