Problem Ultrasonic sensor

Hello, I am a beginner to C++ and I have only done a few projects. Currently, I am trying to make a distance measurer with an ultrasonic sensor (Data sheet). What I want it to do is, when there is something close to the sensor the LED will turn on, however, the LED is always on and there is no error message.

here is the code

const int trigPin = 13;
const int echoPin = 12;

long duration;
int distance;
int led6 = 6;
int led5 = 5;
int led4 = 4;
int led3 = 3;
int led2 = 2;
int led1 = 1;

void setup() {
  pinMode(led6,OUTPUT);
  pinMode(led5,OUTPUT);
  pinMode(led4,OUTPUT);
  pinMode(led3,OUTPUT);
  pinMode(led2,OUTPUT);
  pinMode(led1,OUTPUT);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(trigPin, LOW);
  delay(500);

  digitalWrite(trigPin, HIGH);
  delay(500);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = duration*0.034/2;

  Serial.print("DISTANCE: ");
  Serial.println(distance);

  
  if (distance < 10){
    
    digitalWrite(led6,HIGH);
    digitalWrite(led5,HIGH);
    digitalWrite(led4,HIGH);
    digitalWrite(led3,HIGH);
    digitalWrite(led2,HIGH);
    digitalWrite(led1,HIGH);
  }
    else( digitalWrite(led1, LOW));
    

}

If anyone is able to help it would be greatly appreciated.

What values do your prints show?

Also, why such long delays? Typical trigger pulses are single digit microseconds, though most I’ve seen will trigger on a falling edge.

Here is a link to the circuit and code to do your project:

Have a great day:-)

  digitalWrite(trigPin, HIGH);
  delay(500);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);

Waiting half a second (500 milliseconds) after pulsing the Trigger pin HIGH is causing you to miss the echo pulse. The pulseIn() function doesn’t see a pulse so it times out (1 second) and returns zero. You see 0 as <10 (close) rather than “too far to get an echo from” so you light up the light.

Look at examples of the ultrasonic sensor and you will see delays in the order of a few MICROSECONDS. Take that delay(500) out and check for a 0 return (no echo) from pulseIn().

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