Problem with HC-SR04 measurement

Hi, I am using an Arduino nano AtMega368 and the main problem is that the Ultrasonic Distance sensor HC-SR04 gives me ~890cm with any distance. In my code, I want a red led lights up with the distance in cm<150, and if distance>150, then a green led lights up. But I realized that it's when the green led lights up that the HC-SR04 is measuring falsly, how this sensor works properly with leds ? Thanks

#define trigPin 2
#define echoPin 3
#define led 4
#define led2 5
long duration;
int distance;
void setup() {
 
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
  Serial.begin(9600);
}

void loop() {

  digitalWrite(trigPin, LOW);
  delayMicroseconds(5);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = duration * 0.034 / 2;
  Serial.print("Distance = ");
  Serial.print(distance);
  Serial.println(" cm");
  delay(50);
  if (distance < 150) {  

  digitalWrite(led2,HIGH);
  digitalWrite(led,LOW);
  }  else {
    digitalWrite(led2,LOW);
digitalWrite(led,HIGH);

}}

More members will see your code if posted properly. Read the how get the most out of this forum sticky to see how to properly post code. Remove useless white space and format the code with the IDE autoformat tool (crtl-t or Tools, Auto Format) before posting code in code tags.

I set up a HCSR04 and 2 LEDs on my Uno and tried your code after adding a timeout to the pulseIn() function.

duration = pulseIn(echoPin, HIGH, 30000); // ******* added timeout

Code works fine for me.

I realized that it's when a certain led lights up that the HC-SR04 is going crazy

What LED? What does "crazy" mean?

It may help if you post a schematic and a photo of your wiring.
How to post images.

Hi eddi. Just by reading, your code looks fine.
Maybe some advices :
Get both of your led in a defined state (mainly low) at setup, then let your code manipulates it as required. I used to put somewhere a way to lower the pin (and let the loop put the correct value at next iteration) but looks not required in your code.
Lighting the led up or down is a very good way to indicate a range (supposing the treshold value is known or obvious) and I have numerous facts in mind proving human being likes blinking colored light.
Nevertheless, during decode it is very important you self debug with serial monitor. Leaning on just your request sheet (getting a distance from sensor, then transform it in a yes/no answer), I write 2 printing lines:

Serial.print("distance/cm: "); Serial.println(distance);
Serial.print("less than 150cm: ”);Serial.println(distance<150, BIN);

Then the serial monitor helps you to screen if issue comes to value, or format value, or led managing, or wiring etc..

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