Hi all
I have a strange problem which should be really simple to solve yet I can't see it!
Very briefly, I'm measuring the pulse width and period of a signal by recording the transitions in an interrupt routine; on a rising or falling edge, the value of micros() is stored to work out the duty cycle.
Below is by interrupt routine:
void sensor_interrupt(void)
{
if ((PIND & 0b00001000) == 0b00001000) // If pin is high
{
if (pulseStarted == false) // If we're starting a new pulse...
{
pulseStart = micros();
pulseStarted = true;
}
else
{
pulseEnd = micros(); // Otherwise this is the end of the pulse
pulseStarted = false;
}
}
else
pulsePeriod = micros();
}
And here I am printing out the value of micros() at the various points:
Serial.print(pulseStart);
Serial.print(",");
Serial.print(pulseEnd);
Serial.print(",");
Serial.print(pulsePeriod);
Serial.print(",");
Serial.println(pulseEnd - pulseStart);
What is really strange (to me) is that the 'pulseEnd - pulseStart' calculation usually gives the right answer, but sometimes doesn't! Here's the serial output:
15057568,15058564,15058500,996
16058808,16059800,16059740,992
17060044,17061040,17060976,4294966300
18061284,18062276,18063208,4294966300
19062520,19063516,19064448,996
20063756,20064752,20065684,992
Lines 1 and 2 are correct, 3 and 4 are not and 5 and 6 are!
Since I'm dealing with large numbers I assume there's a math issue somewhere (all variables are unsigned longs) but I can't for the life of me see it!