issues with script

Hey, I’m using an arduino for the first time. I have a ultra sonic distance sensor, HC-SR04.

I have 3 LED lights and want to turn them on one by one when my hand is 30cm, 20cm and 10cm away from the distance sensor. It kinda works but it’s inconsistent, sometimes two LEDs turn on at the same time and sometimes they turn on too early etc.
Here’s my script

const int LED1 = 13;
const int LED2 = 12;
const int LED3 = 11;
const int echoPin = 10;
const int trigPin = 9;
long duration;
int distance;

void setup() {
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(trigPin, OUTPUT);
}

void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);

digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

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

if (distance < 10) {
digitalWrite(LED3, HIGH);
}

else if (distance < 20) {
digitalWrite(LED2, HIGH);
}
else if (distance < 30) {
digitalWrite(LED1, HIGH);
}
else {
digitalWrite(LED1, LOW);
digitalWrite(LED2, LOW);
digitalWrite(LED3, LOW);
}
}

Of course you'll get multiple leds at once if something is moving further away or closer - you only turn the leds off if there's nothing nearby....

well obviously. That's intentional and not the issue I tried describing.

If I start with my hand 40 cm away and slowly move it closer, then at 30cm one LED turns on, then sometimes at like 25cm both the other ones turn on

Put some Serial.print() commands into your program so you can see what values the sensor is actually returning.

…R