使用arduino控制超声传感器HC-SR04测量距离

目录

硬件

软件

接线

测量结果


硬件

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

超声测距演示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值