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);
}