Pages: [1]   Go Down
Author Topic: Fading LED using a light sensor  (Read 556 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 22
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello,


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:
/*
  AnalogReadSerial
 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:
  Serial.begin(9600);
}


// 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;
    delay(80);
    analogWrite(led, brightness);
  }
  else
  {
    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?
Logged

California
Offline Offline
Faraday Member
**
Karma: 92
Posts: 3435
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Pages: [1]   Go Up
Jump to: