Go Down

Topic: Fading LED using a light sensor (Read 2032 times) previous topic - next topic



I have a light sensor, and, if it's dark outside, i want to turn ON an LED with a fading effect.
I have made the program but it doesn't wirok properly:

Code: [Select]

Reads an analog input on pin 0, prints the result to the serial monitor.
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

This example code is in the public domain.
const int led = 3;
// the setup routine runs once when you press reset:
int brightness = 0;    // how bright the LED is
int fadeAmount = 5;    // how many points to fade the LED by

void setup() {
  pinMode (led, OUTPUT);   // sets pin 13 as digital output
  // initialize serial communication at 9600 bits per second:

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  if(sensorValue < 200 )
    brightness = brightness + fadeAmount;
    analogWrite(led, brightness);
    analogWrite(led, 0);
    brightness = 0;

  delay(10);        // delay in between reads for stability

If it's dark outside, the LED is turning ON with the fading effect but as soon as the LED hits 255 brightness, it starts all over again from 0 to 255 brightness.

How can I make the LED stay ON after his brighness goes from 0 to 255?


You're adding fadeAmount to brightness unconditionally, so once it goes above 255, it overflows and starts back near 0. You need some logic to stop adding to it before you go over 255. You can do that with a simple if statement or you can use the constrain() function.

Go Up