CODE
Make
sure you download NewPing library before you code.
// ---------------------------------------------------------------------------
// Example NewPing library sketch with buzzer alert if object is within 10 cm
// ---------------------------------------------------------------------------
#include <NewPing.h>
#define TRIGGER_PIN 2 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 3 // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance to ping for (in centimeters).
#define BUZZER_PIN 7 // Buzzer pin
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup
void setup() {
pinMode(BUZZER_PIN, OUTPUT); // Set buzzer pin as output
Serial.begin(115200); // Start serial monitor
}
void loop() {
delay(50); // Wait 50ms between pings
unsigned int distance = sonar.ping_cm(); // Perform one ping and get distance in cm
Serial.print("Ping: ");
Serial.print(distance);
Serial.println(" cm");
if (distance > 0 && distance <= 10) {
digitalWrite(BUZZER_PIN, HIGH); // Turn buzzer on
} else {
digitalWrite(BUZZER_PIN, LOW); // Turn buzzer off
}
}


0 Comments