Measuring RPM off of an optical tach.
Why does this code;
volatile byte rpmcount;
unsigned int rpm;
unsigned int timeold;
void setup()
{
Serial.begin(9600);
attachInterrupt(1, RPM_Func, RISING);
digitalWrite(2, HIGH);
rpmcount = 0;
rpm = 0;
timeold = 0;
}
void loop()
{
if (rpmcount >= 20) {
unsigned int time_since = millis() - timeold;
rpm = ((rpmcount * 1000) / time_since) * 60;
timeold = millis();
Serial.println(time_since, DEC);
rpmcount = 0;
Serial.println(rpm, DEC);
}
}
void RPM_Func()
{
rpmcount++;
}
...work, but this code;
volatile byte rpmcount;
unsigned long rpm;
unsigned long timeold;
void setup()
{
Serial.begin(9600);
attachInterrupt(1, RPM_Func, RISING);
digitalWrite(2, HIGH);
rpmcount = 0;
rpm = 0;
timeold = 0;
}
void loop()
{
if (rpmcount >= 20) {
unsigned int time_since = millis() - timeold;
rpm = ((rpmcount * 1000000) / time_since) * 60;
timeold = millis();
Serial.println(time_since, DEC);
rpmcount = 0;
Serial.println(rpm, DEC);
}
}
void RPM_Func()
{
rpmcount++;
}
...not?
All I can figure is there's a rollover somewhere but I used unsigned longs, figuring 4.2 billon was big enough. RPM is in the 16 to 140 Hz range.
Any help is appreciated.
-Ian
P.S. For the record, I thought I'd use micros to give me a little more resolution without slowing down the update time by increasing the number of counts it updates on.