define maxLed 13 #define minLed 12 #define trigPin 11 #define echoPin 10 int maximumRange = 200; int minimumRange = 0; int oneThird = (maximumRange - minimumRange) / 3; int twoThird = 2 * oneThird; int maxLedState; int minLedState; void setup() { Serial.begin (9600); pinMode(maxLed, OUTPUT); pinMode(minLed, OUTPUT); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { long duration; long distance; digitalWrite(trigPin, LOW); // Added this line delayMicroseconds(2); // Added this line digitalWrite(trigPin, HIGH); delayMicroseconds(10); // Added this line digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = (duration/2) / 29.1; if ((distance <= minimumRange) || (distance >= maximumRange)) { // out of range maxLedState = LOW; minLedState = LOW; Serial.println("Out of range"); } // out of range else { // in range Serial.print(distance); Serial.println(" cm"); if (oneThird > distance) { // within first 1/3 of range maxLedState = LOW; minLedState = HIGH; } // within first 1/3 of range else if (twoThird > distance) { // within middle of range maxLedState = HIGH; minLedState = HIGH; } // within middle of range else { // at last 1/3 of range maxLedState = HIGH; minLedState = LOW; } // at last 1/3 of range } // in range digitalWrite(minLed,maxLedState); digitalWrite(maxLed,minLedState); delay(500); // wait a bit }