目录
硬件
arduino leonardo一个
面包板一块
若干杜邦线
直尺
超声波测距传感器HC-SR04,购自某宝,不到6元
软件
unsigned int EchoPin = 10;//arduino针脚10接收回波
unsigned int TrigPin = 8;//arduino针脚8触发测量
unsigned long Time_Echo_us = 0;
float Len_mm = 0;
unsigned long Len_Integer = 0;
unsigned int Len_Fraction = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(EchoPin, INPUT);
pinMode(TrigPin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(TrigPin, HIGH);
delayMicroseconds(50);
digitalWrite(TrigPin, LOW);
Time_Echo_us = pulseIn(EchoPin, HIGH, 5000);//等待超过5000us则超时
if(Time_Echo_us < 60000 && Time_Echo_us > 1)
{
Len_mm = (Time_Echo_us * 0.35)/2;//认为当前声速350m/s
Len_Integer = floor(Len_mm);
Len_Fraction = (Len_mm - Len_Integer) * 100;
Serial.print("len = ");
Serial.print(Len_Integer, DEC);
Serial.print(".");
if(Len_Fraction < 10)
Serial.print("0");
Serial.print(Len_Fraction, DEC);
Serial.println("mm");
}
delay(100);//每隔100ms测一次
}
接线
接线
测量结果
这里设置声速350m/s。当物体距离传感器<15cm时,测量值明显偏小,但是>=15cm时测量基本准确。
超声测距演示