I'm trying to use pulseIn
with elapsed time using millis()
, I don't want to use interrupts instead of pulseIn
(I need pulseIn
because I need accurate pulse time), the elapsed time doesn't need to be very accurate, so to calculate the elapsed time I've added to the elapsed time the time the arduino is blocked, The problem is the calculated elapsed is very inaccurate, I suspect it sometimes never enters if(elapsed > 1000*60*2)
, Why is that? How can I fix that?
Thanks.
Code
unsigned long startTime = 0;
unsigned long elapsed = 0;
unsigned int val = 0;
uint32_t time_wait_pulse = 0;
void setup(){
startTime = millis();
}
void f(){
uint32_t time = 0;
time += pulseIn(pin, LOW);
if(time > 0) {
...
time_wait_pulse += time;
} else {
time_wait_pulse += 1000000; //default pulseIn timeout (micros)
}
}
void loop(){
elapsed = millis() - startTime + (unsigned long)(time_wait_pulse/1000);
if(elapsed > 1000*60*2){
val++;
startTime = millis();
time_wait_pulse = 0;
}
noInterrupts();
f();
interrupts();
}