-
1Run a Program
#include
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on ping sensor.
#define ECHO_PIN 11 // Arduino pin tied to echo pin on ping sensor.
#define MAX_DISTANCE 500 // 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;
int flag = 0; // Holds the next ping time.void setup() {
Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
pingTimer = millis();
pinMode(10, OUTPUT); // Start now.
// 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.
}
if (flag == 1)
{
digitalWrite(10, HIGH);delay(500);
digitalWrite(10, LOW);delay(500);
digitalWrite(10, HIGH);delay(500);
digitalWrite(10, LOW);delay(500);
}
else
{
digitalWrite(10, LOW);
}
}void echoCheck() { // Timer2 interrupt calls this function every 24uS where you can check the ping status.
if (sonar.check_timer()) { // This is how you check to see if the ping was received.
// Here's where you can add code.
Serial.print("Ping: ");
Serial.print(sonar.ping_result / US_ROUNDTRIP_CM); // Ping returned, uS result in ping_result, convert to cm with US_ROUNDTRIP_CM.
Serial.println("cm");
if ((sonar.ping_result / US_ROUNDTRIP_CM) < 50)
flag = 1;
else if ((sonar.ping_result / US_ROUNDTRIP_CM) > 50)
flag = 0;
}
}
Discussions
Become a Hackaday.io Member
Create an account to leave a comment. Already have an account? Log In.