Using a Photocell to turn on an LED when it's dark

Hello, I am a little new to using arduino, and I could use a little help. So far I am able to activate an LED when there is light in the room, and deactivate it when the photocell is covered. What I am curious about is how to reverse it so that the LED turns on when there is no light in the room, and turns off when there is light. I know this sounds like the simplest task, but I really have no clue how to go about it. Also is it possible to slowly fade the light when it turns on and off?
Thanks for all the help!

This is the sketch that I have so far:

int lightPin = 0;
int ledPin = 13;

void setup ()
{
  pinMode (ledPin, OUTPUT);
}

void loop ()
{
  int lightLevel = analogRead (lightPin);
  lightLevel = map(lightLevel, 0, 900, 0, 255);
  lightLevel = constrain(lightLevel, 0, 900);
  analogWrite(ledPin,lightLevel);
  
}

Hi,

I think you could try reversing the map function...

lightlevel = map(lightlevel, 0, 900, 255, 0)

Good luck

Yes, reversing the values in the map() function should do it.

The use of the constrain() function in your sketch is wrong. The value from analogRead() will be between 0 and 1023. The value needed by analogWrite must be between 0 and 255. So the constrain() function won't prevent an incorrect value (ie. over 255) going to the analogWrite(). You could move that line so that it is above/before the map() command, but it would only ever effect values from analogRead() that were between 901 and 1023, so I would just get rid of it altogether.

To make the led level change more slowly, here's a technique I like to use. It calculates a sort of running average of the new led level and the old led level, but gives far more weight to the old value than to the new value. So the average value only changes slowly. It put a delay in the loop too, otherwise it will still change too fast.

Try changing the 499 and 500 values (leave the delay() alone). For example try 99 and 100 or 999 and 1000.

int lightPin = 0;
int ledPin = 13;
int ledLevel;

void setup ()
{
  pinMode (ledPin, OUTPUT);
}

void loop ()
{
  int lightLevel = analogRead (lightPin);
  lightLevel = map(lightLevel, 1023, 0, 0, 255);
  ledLevel = (499 * ledLevel + lightLevel) / 500;
  analogWrite(ledPin,ledLevel);
  delay(10);
}