Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Multi HCSR04 Example
Used to read HC-SR04 Ultrasonic Range Sensor(s)
This sketch reads one or more ultrasonic rangefinders and adds the results in cm
to an array which can be read. The result order is the same as the order the
sensor pins are defined in. You must define an adjustment for each sensor
(even if it is 0). this adjustment moves '0' cm some number of cm in front of the
#include "Sonar.h"
#include "Arduino.h"
const int MAX_uS = 38000; // 38 ms if no obstacle detected
const int MAX_CM = 400;
const float adjustments[] = {0}; // adjust how far from each sensor is 0 cm
int sensors[] = {7}; // Ping Pin for each attached sensor
int triggers[] = {9}; // Trigger Pin for each attached sensor
long microsecondsToCentimeters(long microsecs) {
* According to HC-SR04 datasheet,
* ping microseconds / 52 = centimeters traveled
return microsecs / 52 / 2;
void initSonar() {
* The HC-SR04 is triggered by a HIGH pulse of ~10 microseconds.
* Keep LOW beforehand to ensure a clean HIGH pulse.
for(int i=0; i<SONAR_COUNT; i++){
pinMode(triggers[i], OUTPUT);
digitalWrite(triggers[i], LOW);
pinMode(sensors[i], INPUT);
void requestSonar() {
long duration, cm;
for(int i =0;i<SONAR_COUNT;i++){
int triggerPin = triggers[i];
int pingPin = sensors[i];
int adjustment = adjustments[i];
digitalWrite(triggerPin, HIGH);
delayMicroseconds(10); //
digitalWrite(triggerPin, LOW);
* The ping pin is used to read the signal from the HC-SR04. a HIGH pulse
* whose duration is the time (in microseconds) from the sending of the ping
* to the reception of its echo off of an object. Assuming stationary sensors,
* this is twice the distance to the object.
duration = pulseIn(pingPin, HIGH);
if(duration >= MAX_uS){
// No obstacle detected
sonar[i] = MAX_CM - adjustment;
} else {
cm = microsecondsToCentimeters(duration); // convert the time into a distance in cm
sonar[i] = cm - adjustment; //Add the adjusted result to the result set
#define SONAR_COUNT (1)
long sonar[SONAR_COUNT] = {0}; // Output Distances in cm for each sensor
void initSonar();
void requestSonar();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.