Traffic light code

i need help fixing my code so that when i shine light on the photoresistor it turns the light off but when it breaks the light will flash then turn off

int PR = A0; //Analog 0 to Photoresistor
int light = 2; // lightpin

void setup() {

  pinMode(light, OUTPUT);
  
  pinMode(PR, INPUT);


  Serial.begin(9600);
  
  digitalWrite(light, LOW); 
}

void loop() {

  int Read = analogRead(PR);// "Read" reads analog0 data

  Serial.println(Read);// Print that data

  if (Read > 900)
  {

    digitalWrite(light, LOW); // turns on

    delay(1000);

    digitalWrite(light, LOW);

  }

  else //if the value is greater than 120

  {

    digitalWrite(light, HIGH); // turns on

    delay(1000);

    digitalWrite(light, LOW);




  }
}

A small finite state machine comes to mind. It can have three states

  • On
  • Flash
  • Off

You can go from 'Off' to 'On' if there is no light on the sensor, from 'On' to 'Flash' if there is light on the sensor and from 'Flash' to 'Off' after a time has lapsed.

Finite state machines are often implemented using a switch/case.

Your topic is not related to problems with the IDE and hence has been moved to a more suitable location on the forum.

For a start add the flash to the off cycle such that it must flash before turning off. This will get you started but there will be more things as you progress with the assignment.

Both conditions (light shine, light break) result in "off"... do you want "light shine = off" and "light break = flash"? Right now, you turn the light ON, OFF Maybe you want to turn the light ON, OFF, ON, OFF for flashing?

int PR = A0; //Analog 0 to Photoresistor
int light = 2; // lightpin

void setup() {
  pinMode(light, OUTPUT);
  pinMode(PR, INPUT);
  Serial.begin(9600);
  digitalWrite(light, LOW);
}

void loop() {
  int Read = analogRead(PR);// "Read" reads analog0 data
  Serial.println(Read);// Print that data
  if (Read > 900)
  {
    digitalWrite(light, LOW); // turns on <<-- CATHODE TO PIN, ANODE TO VCC
    delay(1000);
    // digitalWrite(light, LOW); // <-- LIGHT WAS "LOW"
  }
  else //if the value is greater than 120 << THIS COMMENT SHOULD READ "IF GREATER OR EQUAL TO 900"
  {
    digitalWrite(light, HIGH); // turns on
    delay(250);
    digitalWrite(light, LOW);
    delay(250);
    digitalWrite(light, HIGH); // turns on
  }
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.