Espruino and an ultrasonic distance sensor

21

The HC-SR04 is used to measure distances by using ultrasonic sounds. It works by sending out a burst of ultrasound and listening for the echo when it bounces off of an object. Here is a picture of the sensor

hc-sr04

The duration of this second pulse is equal to the time taken by the ultrasound to travel to the object and back to the sensor. Using the speed of sound, this time can be converted to distance.

Set low the Trig and Echo port when the module initializes , firstly, transmit at least 10us high level pulse to the Trig pin (module automatically sends eight 40K square wave), and then wait to capture the rising edge output by echo port, at the same time, open the timer to start timing. Next, once again capture the falling edge output by echo port, at the same time, read the time of the counter, which is the ultrasonic running time in the air. According to the formular: test distance = (high level time * ultrasonic spreading velocity in air) / 2, you can calculate the distance to the obstacle.

 

Specifications:

Input voltage: 5v
Current: Less than 2mA
Sensor angle: 15 degrees
Detection distance: 2cm-450cm
Accuracy: Up to 0.3cm
Input trigger signal: 10us TTL impulse
Echo signal : output TTL PWL signal

 

Layout

Here is an image of the layout I used

 

espruino-and-hcsr04_bb

 

Code

 

require("HC-SR04");
 
var sensor = require("HC-SR04").connect(A0,A1,function(dist) {
  console.log(dist+" cm away");
});
setInterval(function() {
  sensor.trigger(); // send pulse
}, 500);

 

Testing

The best way of testing this is to have a ruler, place the HC-SR04 at one end and then an object at the other end and check the distance reported.

Here are some of my results

30.56777151007 cm away
29.68102170709 cm away
30.56777151007 cm away
26.53556957579 cm away
20.22793418482 cm away
14.32184587445 cm away
10.65772876404 cm away
9.30250736705 cm away
7.79670581483 cm away
8.09786612527 cm away
7.01034278200 cm away
5.32468159993 cm away
4.65125368352 cm away

 

Links

 
hc-sr04 ultrasonic ranging module smart car ultrasonic sensor module

Share