#include <NewPing.h>
#define BUZZER 12 // Buzzer output pin
#define TRIG_PIN 7 // Trigger pin of sonar
#define ECHO_PIN 6 // Echo pin of sonar
#define MAX_DISTANCE 300 // Max distance at 3m
int distance;
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
void setup() {
Serial.begin(9600);
pinMode(BUZZER, OUTPUT);
beep(5,200);
}
void loop() {
readDistance();
delay(50);
// put your main code here, to run repeatedly:
}
// Function to sound the buzzer
void beep(int rpt, int deltime){
for (int x=0; x < rpt; x++){
digitalWrite(BUZZER, HIGH);
delay(deltime);
digitalWrite(BUZZER, HIGH);
delay(50);
}
}
// Funcyion to read the distance
void readDistance(){
distance = sonar.ping_cm();
if(distance == 0) distance = 300;
Serial.print("Dist: ");
Serial.print(distance);
Serial.println("cm");
}