Help with programming a traffic light using an ultrasonic sensor

Hello, i am very new programming. I have to create this traffic light in a school project.
I can get the traffic light to run in a loop of 15 seconds but I can’t seem to get the loop to run once the distance in <5 for example. A said I’ve barely any understanding of this, so please bare with me.

Here’s the code:

int trigPin = 10; //Define the pins that you will work with
int echoPin = 9;
int red = 8;
int yellow=13;
int green = 6;
float Speed = 0.0343; // Sound speed at cm/us
long duration, distance;

void setup()
{
pinMode(trigPin, OUTPUT); //Define digital pin 7 as an output

pinMode(echoPin, INPUT); //Define digital pin 8 as an input

pinMode(red, OUTPUT); //Define digital pin 10 as an output

pinMode(green, OUTPUT); //Define digital pin 11 as an output

pinMode(red, OUTPUT);
pinMode(yellow, OUTPUT);
pinMode(green, OUTPUT);
}
void changeLights(){
// green off, yellow on for 3 seconds
digitalWrite(green, LOW);
digitalWrite(yellow, HIGH);
delay(3000);

// turn off yellow, then turn red on for 5 seconds
digitalWrite(yellow, LOW);
digitalWrite(red, HIGH);
delay(5000);

// red and yellow on for 2 seconds (red is already on though)
digitalWrite(yellow, HIGH);
delay(2000);

// turn off red and yellow, then turn on green
digitalWrite(yellow, LOW);
digitalWrite(red, LOW);
digitalWrite(green, HIGH);
delay(3000);
}
void loop() {

digitalWrite(trigPin, LOW); // Make sure that the TRIG is deactivated

delayMicroseconds(2); // Make sure that the TRIG is in LOW

digitalWrite(trigPin, HIGH); // Activate the output pulse
delayMicroseconds(10); // Wait for 10µs, the pulse remains active during this time

digitalWrite(trigPin, LOW); //Stop the pulse and wait for ECHO

duration = pulseIn(echoPin, HIGH) ; // pulseIn measures the time since the defined pin (echoPin) changes its status from low to high (from 0 to 1)

distance = Speed* duration / 2; //Divide by 2 because we want to have only the “go” time, not the “go and back” time
// and divide by 29,1 because 1 is divided by the sound speed (1/SpeedSound) at cm/us

changeLights();
if ( distance < 5);

}

school project?

You actually got what you asked for:

if ( distance < 5);

does nothing at all, and isn’t even followed by any code that would execute if the unintentional ‘;’ were not appended.

So what kind of code should I put after it for it to work?

You should get away with just swapping those lines once you lose that ;

Change:

changeLights();
if ( distance < 5);

… to:

if ( distance < 5)
changeLights();

Thank you! it works now

You're welcome; now, for Bonus Points, make it delay()-less :slight_smile: