How do I dim a set of three LED's with a photoresistor?

This is my first time using Arduino. (Arduino NANO)

I'm working on a project where I have two sets of traffic lights (6 LEDs), that recreate the real life sequence when a button is pressed (think a pedestrian crossing button). I need to add a photoresistor in order to dim all of the LED's dim when the photoresistor is covered.

Here is my code and my attempt to add a photoresistor to dim the LED's. Before I added the code relating to the photoresistor, the sequence is normal, but when I add the code, the lights stay the same brightness and the orange light doesn't turn on.

int greenLed = 5;
int orangeLed = 4;
int redLed = 3;

int pushButton = 7;
int readPushbutton = 0;

int ldr;
int bri;


void setup()
{
  pinMode(A0, INPUT);

  pinMode(greenLed, OUTPUT);
  pinMode(orangeLed, OUTPUT);
  pinMode(redLed, OUTPUT);

  digitalWrite(greenLed, LOW);
  digitalWrite(orangeLed, LOW);
  digitalWrite(redLed, LOW);
  
  pinMode(pushButton, INPUT);
  
  Serial.begin(9600);
}

void loop()
{
  ldr = analogRead(A0);
  bri = map(ldr, 0, 1023, 0, 255);

  int readPushbutton = digitalRead(pushButton);

  if (readPushbutton == 0) {
    	  analogWrite(greenLed, bri);
  		  digitalWrite(orangeLed, LOW);
  		  digitalWrite(redLed, LOW);  
      	  delay(1000);
      
      	
    }
    else if (readPushbutton == 1){
      Serial.println("PEDESTRIAN WAITING");
       	digitalWrite(greenLed,LOW);
  		  analogWrite(orangeLed, bri);
      	digitalWrite(redLed, LOW); 
  		    delay(2000);
      
      	digitalWrite(greenLed,LOW);
   		  digitalWrite(orangeLed,LOW);
  		  analogWrite(redLed,bri);
  		Serial.println("PEDESTRIAN CROSSING");
  		    delay(30000);   
            
    }
  }

If you are using the Arduino Uno/Mini, pin 4 is not PWM.
Therefore analogWrite(orangeLed, bri); it will not work.

Make sure that the external circuit and code to read the LDR returns a reasonable range of values, under different lighting conditions.

Hint:

 bri = map(ldr, 0, 1023, 0, 255);

is equivalent to

 bri = ldr/4;

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