This should be easy but for some reason I cannot get around it. I'm old and realize my brain cells are rapidly dying off.
I have an SR04 ultrasonic detector working fine. When something is detected, it lights an LED. I want to time the interval between the LED going on and then off. I have searched and searched and read many timing sketches using millis() but cannot get the answer I want. If I hold a stick in front of the sensor for 5 seconds, I expect readout of 5 seconds (5000 millis). I get 101 millis or thereabouts no matter how long my stick is in front of the sensor.
There are only two statements that I have to put "somewhere" in order to make this work, the two that use "millis()". Like I said, it should be easy. Can someone point me on the right path? THanks for any help.
void loop() {
//Activate sonar
duration = sonar.ping_median(iterations); //5 iterations to reduce noise
distance = (duration / 2) * 0.0343;// Use 343 metres per second as speed of sound
if (distance < 40) //less than 40 means something is blocking the view
{ digitalWrite(ledPin, HIGH);
}
else
{ digitalWrite(ledPin, LOW);
}
val = digitalRead(ledPin);
if (val == HIGH) {
currentState = 1;
start=millis();
}
else {
currentState = 0;
}
if (currentState != previousState) {
if (currentState == 1){
counter = counter + 1;}
elapsed=millis()-start;
Serial.print("Activated ");
Serial.print(counter);
Serial.println(" times");
Serial.print(" Elapsed ");
Serial.println(elapsed);}
previousState = currentState;
}