目录

硬件

软件

接线

测量结果


硬件

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时测量基本准确。

超声测距演示

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐