Search code examples
c++arduinoledcircuit

Why is the red light not lighting up?


So I am very new to this IoT stuff and what I am trying to create here is somewhat like traffic violation detection.

My idea is: when the red light is on and if the PIR sensor detects movement, the buzzer/LED turns on.

Here's the image:

enter image description here

Here's what the code looks like:

int pir = 2;
int rojo = 12; 
int amarillo = 11;
int verde = 10;
int led = 7;

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() {
  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);
    
  digitalWrite(rojo, HIGH); // It turns on the red led 
  delay(15000); //wait 15 seconds 
  digitalWrite(rojo, LOW);
  if (rojo == HIGH) {
    if (val == HIGH) {
      digitalWrite(led, HIGH);
    } else {
      digitalWrite(led, LOW); 
    }
    delay(10);
  }
}

Solution

  • The problem is here:

      digitalWrite(rojo, HIGH); //It turns on the red led 
      delay(15000); //wait 15 seconds 
      digitalWrite(rojo, LOW);
      if (rojo == HIGH) {
        if (val == HIGH) {
          digitalWrite(led, HIGH);
        } else {
          digitalWrite(led, LOW); 
        }
        delay(10);
      }
    

    First of all, rojo is a pin number, not a value you want to use in this compare.

    Second, during your delay delay(15000), the code stops running, so movement is not detected during this time.

    The only way to detect during the 15s delay is by using millis() for your timing and delay (or using an interrupt).

    You could try something like this (untested):

    digitalWrite(rojo, HIGH); //It turns on 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);
    

    I didn't test this, but you get the idea.

    Note that I don't know if the motion detector returns HIGH or LOW when something moves; you may need to change the code there.