超声波测距原理

超声波测距原理是在超声波发射装置发出超声波,它的根据是接收器接到超声波时的时间差,与雷达测距原理相似。 超声波发射器向某一方向发射超声波,在发射时刻的同时开始计时,超声波在空气中传播,途中碰到障碍物就立即返回来,超声波接收器收到反射波就立即停止计时。(超声波在空气中的传播速度为340m/s,根据计时器记录的时间t(秒),就可以计算出发射点距障碍物的距离(s),即:s=340t/2)

超声波测距原理

US-015 超声波测距模块

US-015是目前市场上分辨率最高,重复测量一致性最好的超声波测距模块;US-015的分辨率高于1mm,可达0.5mm,测距精度高;重复测量一致性好,测距稳定可靠。US-015超声波测距模块可实现2cm~4m的非接触测距功能,供电电压为5V,工作电流为2.2mA,支持GPIO通信模式,工作稳定可靠。

代码

US015_1

US015_2

US015_3

/*
项目:测试距离(单位mm)
原理:声波在空气中传播速度为340m/s,根据计时器记录时间t,即可算出发射点距离障碍物的距离S,即S=340m/s*t/2,这就是所谓的时间差测距法。

//连线方法
//MPU-UNO
//VCC-5V
//GND-GND
//Echo-D2
//Trig-D3
*/

unsigned int EchoPin = 3;          
unsigned int TrigPin = 2;          
unsigned long Time_Echo_us = 0;
unsigned long Len_mm  = 0;

void setup()
{  //Initialize
    Serial.begin(9600);        //Serial: output result to Serial monitor
    pinMode(EchoPin, INPUT);   //Set EchoPin as input, to receive measure result from US-015
    pinMode(TrigPin, OUTPUT);  //Set TrigPin as output, used to send high pusle to trig measurement (>10us)
}

void loop()
{
    digitalWrite(TrigPin, HIGH);    //begin to send a high pulse, then US-015 begin to measure the distance
    delayMicroseconds(20);          //set this high pulse width as 20us (>10us)
    digitalWrite(TrigPin, LOW);     //end this high pulse
   
    Time_Echo_us = pulseIn(EchoPin, HIGH);               //calculate the pulse width at EchoPin,
    if((Time_Echo_us < 60000) && (Time_Echo_us > 1))     //a valid pulse width should be between (1, 60000).
    {
      Len_mm = (Time_Echo_us*34/100)/2;      //calculate the distance by pulse width, Len_mm = (Time_Echo_us * 0.34mm/us) / 2 (mm)
      Serial.print("Present Distance is: ");  //output result to Serial monitor
      Serial.print(Len_mm, DEC);            //output result to Serial monitor
      Serial.println("mm");                 //output result to Serial monitor
    }
    delay(1000);                            //take a measurement every second (1000ms)
}