Why does the green light light up when needed?

  arduino, arduino-ultra-sonic, c++, tinkercad

So here’s what I am trying to achieve when the ultrasonic sensor detects a distance less than a certain amount then the light should turn green allowing the traffic to move
Here's the image of the circuit

Here’s the code

int pir = 2;
int rojo = 12;
int amarillo = 11;
int verde = 10;
int led = 3;
const int pingPin2 = 9; // Trigger Pin of Ultrasonic Sensor
const int echoPin2 = 8;
void setup() {
  pinMode(pir, INPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600);
  pinMode(verde, OUTPUT); //It declares the green pin as output 
  pinMode(amarillo, OUTPUT); //It declares the yellow pin as output 
  pinMode(rojo, OUTPUT);
}

void loop() {
  int distance2;
  distance2 = calculatedistance(pingPin2, echoPin2);
  if (distance2 <= 0.1) {
    digitalWrite(rojo, LOW);
    digitalWrite(verde, HIGH);
    delay(500);
  }

  digitalWrite(verde, HIGH); //It turns on the green led 
  delay(15000); //wait 15 seconds 
  digitalWrite(verde, LOW); //It turns off the green led 
  delay(250); //wait 0.25 seconds

  digitalWrite(amarillo, HIGH); //It turns on the yellow led 
  delay(3000); //wait 3 seconds 
  digitalWrite(amarillo, LOW); //It turns off the yellow led 
  delay(250); //wait 0.25 seconds
  int val = digitalRead(pir);
  Serial.println(val);
  int val1 = digitalRead(rojo);
  digitalWrite(rojo, HIGH); //It turns the red led 

  unsigned long int redStartTime = millis();
  while (millis() - redStartTime <= 15000) {
    delay(100);
    int val = digitalRead(pir);
    if (val == HIGH) {
      digitalWrite(led, HIGH);

    } else {
      digitalWrite(led, LOW);
    }
  }
  digitalWrite(rojo, LOW);
}

long microsecondsToCentimeters(long microseconds) {
  return microseconds / 29 / 2;
}
int calculatedistance(int pingPin, int echoPin) {
  long duration, inches, cm, meter;
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(pingPin, LOW);

  pinMode(echoPin, INPUT);
  duration = pulseIn(echoPin, HIGH);

  cm = microsecondsToCentimeters(duration);
  meter = cm / 100;
  return meter;
}

Can someone help me achieve the desired results.
Also one more question if i wnat to check the value of a variable using printf or something similar in these environment how do i do it?
Thanks in advance

Source: Windows Questions C++

LEAVE A COMMENT