Skip to content

Instantly share code, notes, and snippets.

@dansku
Last active March 2, 2020 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dansku/8da3de4361e9e3921bb5d0aa963445a0 to your computer and use it in GitHub Desktop.
Save dansku/8da3de4361e9e3921bb5d0aa963445a0 to your computer and use it in GitHub Desktop.
/*
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);
}
@hyankov
Copy link

hyankov commented Mar 2, 2020

Weird, NewPing already supports NewPing::timer_ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment