Skip to main content
  1. Posts/

HC-RS04 NewPing Class

Non-blocking C++ class for multiple ultrasonic sensors using inheritance and 30ms timing magic

··285 words·2 mins
sonar non blocking sonar

Just finished writing a small C++ class to work with multiple HC-RS04 sonar transducers in a non-blocking way with the NewPing Library.
In this exact code, I connected two sensors, but you can add as many as you like.

To add new sonars, just create a new instance of it adding the echo and trigger pins.

 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
	Daniel Andrade - www.danielandrade.net
 	non blocking classes for NewPing sonars
*/

#include <NewPing.h>

class Sonar : public NewPing
{
	// Class Member Variables
	// Initialized
	int trigPin;	// Trigger
	int echoPin;	// Echo

	// Current Readings
	int distance;					// measured distance
	unsigned long previousMillis;	// last time we did a reading

	// Constructor - creates a sonar
	// and initialize member variables
	public : Sonar(int trig, int echo) : NewPing(trig, echo, 90), trigPin(trig), echoPin(echo), previousMillis(0)
	{

	}

	void updateSonar()
	{
		// check if the time has passed (more than 30ms)
		unsigned long currentMillis = millis();

		// if it has passed more than 30ms
		if(currentMillis - previousMillis >= 30)
		{
			previousMillis = millis();
			// read current distance
			distance = ping_cm();
		}
	}

	int currentDistance() { return distance; }
};

// Create the instances for our sonars
Sonar sonar1(2,3);
Sonar sonar2(5,4);

void setup()
{

}

void loop()
{
	sonar1.updateSonar();
	sonar2.updateSonar();

	int distance1 = sonar1.currentDistance();
	int distance2 = sonar2.currentDistance();

	Serial.print(distance1);
	Serial.print(" - ");
	Serial.println(distance2);
}

Sonar sonar1(2,3)

Cheers!