I have a project that has a pendulum and trying to record the total time it takes for the pendulum to cross over two LDR's. It swings from left to right then right to left. Underneath the pendulum are two LDR's ldrPin1 which is on the right side of pendulum and ldrPin2 which is on the left side of the pendulum. When the pendulum starts moving to the right, the shadow of the pendulum covers ldrpin1 lowering the threshold of ldrPin1 starting timer, the pendulum moves past ldrPin1 then comes back retracing its path. it is now moving right to left and crosses over ldrPin1 for a second time and continues on the path moving over ldrPin2 which stops the timer.
Everything works as it should (starting the timer and stopping the timer) however, when the pendulum starts its path right to left and crosses over ldrPin1 for the second time the timer is reset to 0.00 and starts again and records the time from the second pass over ldrPin1 and ldrPin2 resulting a shorter amount of time. I need for the timer to record the total time from when the pendulum starts moving and when it crosses over the second LDR, ldrPin2.
const int THRESHOLD_LOW = 530;
const int THRESHOLD_HIGH = 565;
int ldrPin1 = A0;
int ldrPin2= A5;
int HystereticRead (int pin, int previousState){
int photo = analogRead (pin);
if (previousState == LOW && photo >= THRESHOLD_HIGH){
return HIGH;
}
else if (previousState == HIGH && photo < THRESHOLD_LOW){
return LOW;
}
else {
return previousState;
}
}
void setup() {
Serial.begin (9600);
}
void loop() {
static int state0, state1;
static double time0, time1, time2;
int new_state = HystereticRead (A0, state0);
if (state0 == LOW && new_state == HIGH){
time0 = millis ();
}
state0 = new_state;
new_state = HystereticRead (A5, state1);
if (state1 == LOW && new_state == HIGH){
time1 = millis ();
time2 = (time1 - time0)/1000;
Serial.println ("time passed: (s)");
Serial.println (time2);
}
state1 = new_state;
}