Hey guys,
Thanks for the info. I had a suspicion that I needed a latching sensor. Anyways, I learned something along the way, and now I understand a little better how the while() loop works. I'm placing an order for latching hall effect sensors now
I got the previous bit of code to work, it just is not accurate enough because the signal is really "bouncy" when going from LOW to HIGH, and there is actually a very short duration where the signal is HIGH for a few millis while the magnet is passing by the sensor, which is giving it a false reading of 0 or 1 for the elapsed time, but it does return the correct value for elapsed time when it first changes to HIGH. I'm sure there is a way around this problem, and while I'm waiting for the latching type sensor I would love to try and figure it out.
Any ideas or hints? my modified sketch is below:
int startTime;
int stopTime;
int elapsedTime;
int val;
int state;
int time;
int threshold=520; //sets threshold to 520, this must be calibarated for each sensor
void setup(){
Serial.begin(9600);
}
void check() {
val = analogRead(0);
if(val < threshold) //checks to see if the value is less than the set threshold
state=LOW; //this then sets the state to either low or high
else
state=HIGH;
}
int getTimeValue() { //if state is HIGH(magnet present) then assign current millis value to time variable and return that value
check();
if(state == HIGH) {
time = millis();
delay(100);
}
return time;
}
void loop() {
check();
startTime = getTimeValue(); //if the state is HIGH (magnet is present) assign current millis value to startTime
check(); //checking to see what the state is, HIGH or LOW
while(state == LOW) { //this is the new while() statement that constantly checks for the signal to go HIGH
check();
}
check();
stopTime = getTimeValue(); //if it is HIGH again, assign new millis value to stopTime
Serial.println("Elapsed Time: ");
elapsedTime = (stopTime - startTime); // calculate the difference, should give elapsed time
Serial.print(elapsedTime);
}