LDR Light Sensor, Interrupt Executes multiple times!

Hi all,

I have an LDR light sensor connected to my Arduino. It has 4 pins; GND, VCC, A and D. I am not using the analogue pin. Below is the wiring:

Sensor Arduino
VCC 5V
GND GND
D D2

I want the output of the sensor to be called (printed) only when the state changes.
For example, if I turn the light on (from being off) it has retrieved the value multiple times. Then if I turn the light off again, it executes the interrupt code multiple times again.

I have to use the interrupts because it will be used in a near real-time project.
So essentially when the sensor detects light, then the interrupt should be executed once. Only when the light goes off and then back on the interrupt should be executed again.

The working code is below:

#define Light 2
int i = 0;

void setup() {
  Serial.begin(115200);
  attachInterrupt(digitalPinToInterrupt(Light), lightState, RISING);
}

void lightState() {
  i++;
  Serial.println(i);
}

void loop() {
  // put your main code here, to run repeatedly:
}

Screenshots of the com interface are also attached.

Questions:
Why is an unexpected behaviour being produced?
What am I doing Wrong?
How can I resolve this problem?

Thank you, any response will be appreciated.

Darium_Sara:
I have to use the interrupts because it will be used in a near real-time project.

Total nonsense. A halfway decent program can easily check the LDR state like a hundred times in the time it takes the LDR to even react to the change in light levels.

When the voltage gets to the tipping point of the pin (between high and low levels) it may change back and forth a few times. That's in part due to the slowness of the LDR, and your interrupt sees them all. So after the first change you have to "debounce" the LDR by simply ignoring new changes for some time. As you light an LED you no doubt have human observers, making a 50 ms delay (which is a very long time for an Arduino) unnoticeable.

Attaching screen shots of the serial monitor is silly - you can convey the information just as well if not better by copy/pasting the text into your post. The info in those screen shots is rather useless to boot.

Darium_Sara:
So essentially when the sensor detects light, then the interrupt should be executed once. Only when the light goes off and then back on the interrupt should be executed again.

As @wvmarle notes interrupts are not necessary for this project.

The 'state change detection' example in IDE -> file/examples/digital can be readily adapted to do what you want.