#define trg 15
#define ech 4
long pulse_echo;
float distance;
#define sw1 34
#define sw2 35
int f = 1;
void setup() {
Serial.begin(115200);
pinMode(trg, OUTPUT);
pinMode(ech, INPUT);
pinMode(sw1,INPUT_PULLUP);
pinMode(sw2,INPUT_PULLUP);
}
void loop() {
digitalWrite(trg, LOW);
delay(10);
digitalWrite(trg, HIGH);
delayMicroseconds(10);
digitalWrite(trg,LOW);
pulse_echo=pulseIn(ech,HIGH);
distance=(pulse_echo/2.0)/29.0;
if(digitalRead(sw1)==LOW){
delay(20);
f=1;
while(digitalRead(sw1)==LOW){
delay(10);
}
}
if(digitalRead(sw2)==LOW){
delay(20);
f=2;
while(digitalRead(sw2)==LOW){
delay(10);
}
}
if(distance <= 50){
if(f==1){
Serial.print(distance);
Serial.println(" cm");
}else if(f==2){
distance = 2.54/distance;
Serial.print(distance);
Serial.println(" inch");
}
Serial.println("Object Detects");
}else{
if(f==1){
Serial.print(distance);
Serial.println(" cm");
}else if(f==2){
Serial.print(distance);
Serial.println(" inch");
}
Serial.println("No Object Detects");
delay(200);
}
}