const int trigpin = 7;
const int echopin = 6;
int redled = 11;
int greenled = 12;
long duration;
int distance;
void setup() {
pinMode(trigpin, OUTPUT);
pinMode(echopin, INPUT);
pinMode(redled, OUTPUT);
pinMode(greenled, OUTPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trigpin, LOW);
delay(2);
digitalWrite(trigpin, HIGH);
delay(10);
digitalWrite(trigpin, LOW);
duration = pulseIn(echopin,HIGH);
//change the duration to cm and find half of it as the distance
distance = (duration*0.0343)/2;
//we just print the distance on the serial monitor now
Serial.print("Distance = ");
Serial.println(distance);
delay(100);
digitalWrite(redled, LOW);
digitalWrite(greenled, LOW);
if (distance < 25) {
digitalWrite(greenled, HIGH);
}
else {
digitalWrite(redled, HIGH);
}
delay(100);
}