# Timing using a photocell

Hi. I'm new to Arduino and I'm currently trying to build a timing device using Arduino (actually Adafruit Metro M0 Express). I want to use it to measure the shutter speed for some old shutters. My idea is to use a photocell, when shutter is closed, the analog readout is around 300; ~1000 when it opens. Just to be safe, I set the threshold to 500. I get a bunch of 0 while the shutter is closed, which I understand since t = 0, but as soon as I opened the shutter, it outputs nothing, even after I closed the shutter. It seems stuck at line 20 "while (raw > 500) {}". What's wrong with my code? Thanks!
Here is my code:

``````int analogPin = A0;
int raw = 0;
int start = 0;
int finish = 0;
int t = 0;

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
// put your main code here, to run repeatedly:
raw = analogRead(analogPin);

if (raw == 500) {
start = millis(); //get time when shutter opens
}

while (raw > 500) {} //do nothing while shutter stays open

if (raw == 500) {
finish = millis(); //get time when shutter closes
}

t = finish - start;

Serial.println(t);

}
``````

This is an infinite loop, because "raw" is never updated within it.

``````  while (raw > 500) {} //do nothing while shutter stays open
``````

If your photocell is an LDR (light dependent resistor), keep in mind that those are slow. Photodiodes are much faster and so are used for timing.

... and after fixing that infinite loop, you will immediately run into the next problem:

``````  if (raw == 500) {
finish = millis(); //get time when shutter closes
}
``````

Now what if raw drops right through 500 to 499 or even less?

@wvmarle beat me to it.

jremington:
If your photocell is an LDR (light dependent resistor), keep in mind that those are slow. Photodiodes are much faster and so are used for timing.

And even then, you can't guarantee that raw will pass through the value 500 on its way to open/close.

Look for raw > 499 while checking opening. When this *change * happens, mark the start time. See IDE -> file/examples/digital/stateChangeDetection.

Same thing applies going in the other direction when raw drops below 500 - note that *change * and record stop time.

Thanks for your replies. Ive already solved all problems just after realized i run into the same infinite loop problem a few days ago using java... I also changed == to > and <, voila problem solved