Last active
November 12, 2015 22:02
-
-
Save Linkaan/6b2117ea31fa634e77e3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <NewPing.h> | |
#define MAX_TIME 17202 | |
#define TRIGGER_PIN 10 // Arduino pin tied to trigger pin on ping sensor. | |
#define ECHO_PIN 9 // Arduino pin tied to echo pin on ping sensor. | |
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. | |
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. | |
unsigned int pingSpeed = 50; // How frequently are we going to send out a ping (in milliseconds). 50ms would be 20 times a second. | |
unsigned long pingTimer; // Holds the next ping time. | |
unsigned int iterations = 5; | |
float g = 0.95f; // this is a coefficient between 0.0 and 1.0 | |
// the higher it is the more "inert" the filter will be | |
float avg_time = MAX_TIME; | |
float avg_dt = 0.0f; | |
float dt_hysteresis = 1.0f; | |
void setup() { | |
Serial.begin(9600); // Open serial monitor at 9600 baud to see ping results. | |
pingTimer = millis(); // Start now. | |
} | |
void loop() { | |
// Notice how there's no delays in this sketch to allow you to do other processing in-line while doing distance pings. | |
if (millis() >= pingTimer) { // pingSpeed milliseconds since last ping, do another ping. | |
pingTimer += pingSpeed; // Set the next ping time. | |
sonar.ping_timer(echoCheck); // Send out the ping, calls "echoCheck" function every 24uS where you can check the ping status. | |
} | |
// Do other stuff here, really. Think of it as multi-tasking. | |
} | |
void echoCheck() { // Timer2 interrupt calls this function every 24uS where you can check the ping status. | |
// Don't do anything here! | |
uint8_t rc = sonar.check_timer(); | |
if(rc==0) { // This is how you check to see if the ping was received. | |
float echo_time = (float) sonar.ping_result; | |
if(avg_time == MAX_TIME) { | |
avg_time = echo_time; | |
avg_dt = 0.0f; | |
}else { | |
float prev_avg_time = avg_time; | |
avg_time = avg_time * g + (1.0f - g) * echo_time; | |
avg_dt = avg_dt * g + (1.0f - g) * (avg_time - prev_avg_time); | |
if(avg_dt < -dt_hysteresis || avg_dt > +dt_hysteresis) { | |
avg_time = MAX_TIME; | |
Serial.print("motion event, at "); | |
Serial.println(millis()); | |
Serial.print("avg_dt is "); | |
Serial.println(avg_dt); | |
} | |
} | |
iterations = 5; | |
}else if(rc > 1 && --iterations == 0) { | |
avg_time = MAX_TIME; | |
iterations = 5; | |
} | |
// Don't do anything here! | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment