# Calculating MPH from Revolutions Interrupt

Hi all,

I’m building a circuit to display the current speed of a wheel in MPH using LED’s. My program uses an interrupt every revolution to increment a value. I know this works as the following code lights up an extra light every 5 revolutions:

long mph;
volatile int revcount;
long timeold;
long circumference;

void setup() {
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);
pinMode(2, INPUT); // Make digital 2 an input
digitalWrite(2, HIGH); // Enable pull up resistor
attachInterrupt(0, RPMfun, FALLING);
revcount = 0;
mph = 0;
circumference = radius * 2 * 3.141592;
timeold = 0;
}

void RPMfun()
{
digitalWrite(2, HIGH);
revcount++;
}

void loop() {

if (revcount >= 5) {
mph++;
revcount = 0;
}

else if (mph < 1) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 0);
digitalWrite(latchPin, 1);
}
else if (mph < 2) {
digitalWrite(latchPin, 0);
shiftOut(dataPin, clockPin, 0);
shiftOut(dataPin, clockPin, 1);
digitalWrite(latchPin, 1);
}

etc etc etc

Now with this code working I thought i could replace:

if (revcount >= 5) {
mph++;
revcount = 0;

}

with

if (revcount >= 5) {
mph = (revcount * 1000 * 60 *60 *0.621371 * circumference ) / ((millis() - timeold) * 1000000);
timeold = millis();
revcount = 0;

}

but this doesn’t work! No lights are showed at whatever speed i rotate the wheel. Also sorry for the horribly big MPH equation but i like to keep it clear in my head for checking

Does anyone have any ideas why this wouldn’t work?

Not sure why you enable the pull-ups on pin 2 each time you get an interrupt?

Yeah, just did that because whenever the magnet passed it to fire the interrupt it was dragged LOW so the next magnet pass wasn't detected. Adding that line seemed to sort it out. Ideally on my next iteration i'll put a physical pull up resistor on that pin which would probably remove the need for that.

I had planned to work out speed by simply counting every pulse. Program in the number of pulses per mile. Then work out the previous count and the current count at set durations (250ms etc) and then work out the distance... you have the time... then you have the speed.

At least that's the theory.

You only need to enable the pull-up once, say in "setup ()". You should always aim to keep what's in an interrupt service routine to the bare minimum.