Ultraonic sensor not working properly

//define Pins
int led = 13;
int trigPin = 9;
int echoPin = 8;

// defines variables
long duration;
int distance;

void setup() 
{
  //Sets the Led as an Output
pinMode(led, OUTPUT);
// Sets the trigPin as an Output
pinMode(trigPin, OUTPUT);
// Sets the echoPin as an Input 
pinMode(echoPin, INPUT);
// Starts the serial communication 
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);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
if ( distance <= 14 ) // Change Distance according to Ultrasonic Sensor Placement
 {
digitalWrite (led , HIGH );
delay (5000);
 } 
else 
{
digitalWrite (led, LOW );
 }

}

As shown in the code, the LED is supposed to light only when there's something in front of it with the distance less than the value that I have set.


This is the reading read by the ultrasonic sensor, but there was nothing in front of it.

What is the problem? I tried using another ultrasonic sensor, but the result is still the same.

What is the source of your sketch?

On a brief look I saw no code in it showing where the sensor gets its input from? Shouldn't it have an #include library.h statement?

1 Like

Is the sensor pointing to infinity? There has to be something in front of it, the Sky, Wall, etc.

To be exact, it's facing the ceiling the whole time

What do you mean exactly? This is my first time using this.

One problem is that there should be a delay of about 30 to 50 milliseconds between every ping, to allow echos to die. Otherwise, the poor thing gets confused.

In your code, there will only be a significant delay between pings if distance is <= 14 (other than the delay caused by printing to serial at the glacially slow 9600 baud).

Try adding a delay here:

{
   digitalWrite (led, LOW );
   delay (50); //<<--------------------- 
  }
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.