You are asking about
the time difference between two photoresistors
This, to start with, makes little sense. Photoresistors are analog
devices. Their resistance, and thus the voltage you measure, is a
continuously varying quantity. The first thing you have to do is to turn
them into logic (i.e. either “off” or “on”) devices. The simplest
approach is to compare your analog reading to a threshold:
- if the reading is above the threshold, you will say LDR is in the
HIGH
state
- if it is below the threshold, the LDR is in the
LOW
state.
There is a problem with this simple approach though: when the reading is
close to the threshold, the ambient noise can make many spurious
transitions between LOW
and HIGH
. The simplest solution is to have
not one, but two thresholds. This is called “hysteresis” and is
something you definitely should have whenever you are using thresholds
against analog readings. This can be coded as follows:
const int THRESHOLD_LOW = 400; // dummy value
const int THRESHOLD_HIGH = 600; // dummy value
int HystereticRead(uint8_t pin, int previousState)
{
int reading = analogRead(pin);
if (previousState == LOW && reading >= THRESHOLD_HIGH) {
return HIGH;
} else if (previousState == HIGH && reading < THRESHOLD_LOW) {
return LOW;
} else {
return previousState;
}
}
Obviously, the thresholds you will use will not be these dummy values:
you will determine them from experiment.
Next thing is to record transitions. You do not want to look for a
particular state of the LDR, but for the moment it moves from one state
(say LOW
) to the other. This is done by comparing the new state you
read to the previous one, as in:
static int state0; // state of the LDR 0
int new_state = HystereticRead(A0, state0);
if (state0 == LOW && new_state == HIGH) {
// LDR 0 went from LOW to HIGH.
}
state0 = new_state; // save for next time
Last thing, and really the simplest, is to record times. You just have
to call millis()
to get a timestamp, and compute a difference between
timestamps to get a duration in milliseconds. Here is how you could
write it:
void loop()
{
static int state0, state1; // states of the LDRs
static uint32_t time0; // last time LDR 0 went HIGH
// Check for LDR 0 going HIGH.
int new_state = HystereticRead(A0, state0);
if (state0 == LOW && new_state == HIGH) {
time0 = millis();
}
state0 = new_state;
// Check for LDR 1 going HIGH.
new_state = HystereticRead(A1, state1);
if (state1 == LOW && new_state == HIGH) {
uint32_t time1 = millis();
Serial.print(time1 - time0);
Serial.println(" ms");
}
state1 = new_state;
}