【超聲波測距模塊】-【機器人的耳朵】
#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;
}
}
}
}