Ultrasonic Sensor HC-SR04 with LEDs continuously flashing

Hello, I turn to you with the issue that I've created a "distance meter" where I use the Ultrasonic Sensor HC-SR04 with 4 LEDs. The 4 LEDs continuously light up based on distance, with more LEDs lighting up as the object gets closer. My problem is that when none or only some of the LEDs are lit because the distance is beyond 30cm, the LEDs flash simultaneously for a very brief moment. However, when I disconnect the sensor's GND, the flashing stops. Could someone help me with this?
Here is the code, wiring and a video.

Thanks in advance.

const int trig = 3;
const int echo = 2;

const int LED1 = 5;
const int LED2 = 6;
const int LED3 = 7;
const int LED4 = 8;

int duration = 0;
int distance = 0;

void setup() 
{
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  digitalWrite(trig, HIGH);
  delayMicroseconds(1000);
  digitalWrite(trig, LOW);

  duration = pulseIn(echo, HIGH);
  distance = duration / 57.0;  // Adjusted the conversion factor for more accuracy
  Serial.println(distance);

  updateLED(LED1, 30);
  updateLED(LED2, 20);
  updateLED(LED3, 10);
  updateLED(LED4, 5);
}

void updateLED(int ledPin, int threshold)
{
  digitalWrite(ledPin, distance <= threshold);
}

In the simulator it worked correctly.

I tested with the value 57 and then changed the division by 500 to make it easier to see.

distance = duration / 57.0;

distance = duration / 500.0;

Still the same :frowning:

Solution:

duration = pulseIn(echo, HIGH);
delay(100);  //Need to put here delay and the flashing stops
distance = duration / 54.0

What is the best value for the resistor?

Best, shmest -- 510Ω.

1 Like

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