Skip to content

Instantly share code, notes, and snippets.

@dydx
Created July 18, 2012 21:24
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 dydx/3139005 to your computer and use it in GitHub Desktop.
Save dydx/3139005 to your computer and use it in GitHub Desktop.
Calibrate and test a Parallax PING))) Sensor
#include <Ping.h>
Ping ping = Ping(12, 0, 0);
boolean is_calibrated = false;
float calibration_distance = 0.00;
float current_distance = 0.00;
int alarm_pin = 13;
// because my IO shield is fubar
// and has H/L mixed
#define ON LOW
#define OFF HIGH
void setup() {
Serial.begin(9600);
pinMode(alarm_pin, OUTPUT);
}
void loop() {
if(!is_calibrated) {
calibration_distance = get_calibration_distance();
is_calibrated = true;
Serial.println("PING Calibration Successful");
Serial.print("PING Distance Set at: ");
Serial.print(calibration_distance);
Serial.print(" cm");
Serial.println();
}
if(!is_calibrated) {
Serial.println("PING Failed Calibration Routine");
}
if(is_calibrated) {
ping.fire();
Serial.print("PING Distance: ");
Serial.print(ping.centimeters());
Serial.print(" cm");
Serial.println();
}
delay(1000);
/**
trigger alarm if current measured distance deviates from
calibrated distance by more than +/- 2.00 cm
*/
if(is_calibrated) {
ping.fire();
current_distance = ping.centimeters();
if((current_distance > calibration_distance + 2.00) || (current_distance < calibration_distance - 2.00)) {
digitalWrite(alarm_pin, ON);
} else {
digitalWrite(alarm_pin, OFF);
}
}
}
float get_calibration_distance() {
// debugging
float calibration_total = 0.00;
Serial.print("Calibrating");
for( int i = 0; i <= 9; i++) {
ping.fire();
calibration_total += ping.centimeters();
// debugging
Serial.print(" .");
delay(1000);
}
Serial.println(" OK");
return calibration_total/10.00; // # average distance
}
@dydx
Copy link
Author

dydx commented Oct 30, 2013

Could probably add some error checking in the main part of loop() to verify that get_calibration_distance() succeeded before setting is_calibrated to TRUE.

@Givy
Copy link

Givy commented Mar 15, 2018

How do I get a copy of the <Ping.h> file.

Thanks.

Givi

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