LDR change over time

Hi all,
I want to use a LDR to measure when the light in a room is switched off. During the day the light in the room will fluctuate due to sunlight. What I would like to achieve is that the Arduino only switches on a LED, when the sensor reading drops more than 200 compared with a previous reading one second before. So basically it only detects when the sensorvalue drops fast in a short period of time.

I've currently made the code below, which seems to kind of work, but I think it can be done more precise and solid.
What is the best way to do this?

Thanks in advance!

int LDR = A0; //analog pin 0
unsigned long time;
int value[50];
int previous[50];
int i = 0;
int j = 0;
int ledPin = 13;

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

void loop(){
  time = millis();
  value[i] = analogRead(LDR);
  i = (i + 1) % 50;   // modulo operator rolls over variable  
  previous[j] =  value[i-1];
if ((value[i]-previous[j]) > 200 ){
  if (ledPin == LOW){
  digitalWrite(ledPin, HIGH);   // sets the LED on
    if (ledPin == HIGH){
  digitalWrite(ledPin, LOW);   // sets the LED on


How did you decide that the sensor value should drop by 200?

I would determine the cutoff levels empirically, by gathering data for a number of days under various weather and lighting conditions, and then decide what values would be appropriate.

When you use a resistor and a LDR, the curve is like a logarithmic curve. A value of 200 doesn’t say much, as jreminton pointed out.

You have sunk into the code swamp.
It is not clear what the sketch is doing, and what the arrays are for. Your indents are not consistent and its needs more comments. Because of that, a mistake is easily made, and you made one because the value of ‘j’ stays 0.

One whole second is a long time. A cloud in front of the sun could do that. Let’s make it shorter.
The most simple code would remember the previous value. During the analog-to-digital conversion, the light can be switched off, so it would be better to remember two previous samples. But the next example only remembers the previous value.

// untested example.

#define MAX_CHANGE 200
const int LDR = A0;    //analog pin 0
int value;
int previous;
const int ledPin = 13;

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

  // set start values.
  value = previous = analogRead(LDR);

void loop(){
  value = analogRead(LDR);
  if ((value - previous) > MAX_CHANGE) {
    if (ledPin == LOW) {
      digitalWrite(ledPin, HIGH);   // sets the LED on
    } else {
      digitalWrite(ledPin, LOW);   // sets the LED off

  // remember previous value
  previous = value;