const int trigpin = 5;
const int echopin = 7;
const int led = 13;
const int sensor = 4;
int state = LOW;
int val = 0;
//define sound speed in cm/us
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
#define BUZZER_PIN 2
long duration;
float distanceCm;
float distanceInch;
void setup() {
Serial.begin(115200);//starts the serial communication
pinMode(trigpin, OUTPUT);// Sets the trigPin as an Output
pinMode(echopin, INPUT);//Sets the echoPin as an Input
pinMode(BUZZER_PIN, OUTPUT);
pinMode(led,OUTPUT);
pinMode(sensor,INPUT);
Serial.begin(9600);
}
void loop() {
// Clears the trigPin
digitalWrite(trigpin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigpin, HIGH);
delayMicroseconds(10);
digitalWrite(trigpin, LOW);
// Reads the echopin, returns the sound wave travel time in microseconds
duration= pulseIn(echopin, HIGH);
// Calculate the distance
distanceCm = duration*SOUND_SPEED/2;
// Convert to inches
distanceInch=distanceCm*CM_TO_INCH;
// Prints the distance in the Serial Monitor
if(distanceCm>0)
{
digitalWrite(BUZZER_PIN, HIGH);
delay(3000);
Serial.print("Object detected\n");
Serial.println(distanceInch);
}
else
{
digitalWrite(BUZZER_PIN, LOW);
Serial.print("No Object detected");
}
delay(1000);
val=digitalRead(sensor);
if(val==HIGH){
digitalWrite(led,HIGH);
delay(2000);
}
else{
digitalWrite(led,LOW);
delay(2000);
}
}