2017/06/26

Working with HC-SR04 Ultrasonic Sensor

This is a brief summary of how to use HC-SR04 ultrasonic sensor.

Schematic



Note that HC-SR04 is a 5V device, it needs to be powered by 5V and the signal level is 5V. A 5V -> 3.3V level shifter or voltage divider for the Echo Pin (which outputs +5V when the returned pulse is received) is required when HC-SR04 is interfacing with 3.3V device such as Raspberry Pi and ESP8266.

Voltage Divider (for the Echo Pin)


Arduino Sketch (without using the New Ping Library)

The sketch below doesn't use the new ping library.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#define trigPin 3
#define echoPin 2

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  long duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  if (distance >= 200 || distance <= 0){
    Serial.println("Out of range");
  }
  else {
    Serial.print(distance);
    Serial.println(" cm");
  }
  delay(500);
}

Arduino Sketch (using the New Ping Library)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <NewPing.h>
 
#define TRIGGER_PIN  3
#define ECHO_PIN     2
#define MAX_DISTANCE 200
 
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
 
void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(50);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

Somehow I cannot tell there is much difference in the result from not using the newping library and from using the newping library. For cross-platform compatibility sake, perhaps, it's better not to use the newping library (the sketch using the newping library will fail the compilation for ESP8266 and the solution is to use a version of newping library developed for ESP8266 - see the last link in the reference section below for detail.).

Reference:

https://forum.arduino.cc/index.php?topic=243076.0

NewPing Library for Arduino
http://playground.arduino.cc/Code/NewPing

Ultrasonic library for esp 8266 using arduino ide
http://www.esp8266.com/viewtopic.php?p=30256

No comments:

Post a Comment