I have wrote this code for arduino to turn the LED light off when an object is not detected and the LED light on when an object is detected, although the code is not working. How can I improve this?
#define trigPin 12
#define echoPin 11
int ledPin= 1; //Connect LEd pin to 6
int duration, distance; //to measure the distance and time
taken
void setup() {
Serial.begin (9600);
//Define the output and input objects(devices)
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT);
}
void loop() {
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
//when distance is greater than or equal to 200 OR less than or
equal to 0,the buzzer and LED are off
if (distance >= 200 || distance <= 0)
{
Serial.println("no object detected");
digitalWrite(ledPin,LOW);
}
else {
Serial.println("object detected \n");
Serial.print("distance= ");
Serial.print(distance); //prints the distance if it is between the
range 0 to 200
digitalWrite(ledPin,HIGH);
}
}
Answer :- The code is correct logically. But as "distance & duration" have been defined with data type "int" it may fail to run as required. Note that function "pulseIn" returns value of type "unsigned long". So these two variables must be of type "unsigned long".
Second, inside " if " we should test with condition "distance >= 200 || distace < 0" and not less than equal to zero. Most of the time variable distance will have value in between 0 and 1 but due to "int" type it will be made to zero which will make condtion to be true and led will not glow.
Get Answers For Free
Most questions answered within 1 hours.