You could do something simple like this for the counting of pulses, I think. Interrupts 0 and 1 link to pins 2 or 3 most of the time. Whenever it's time to estimate speed, you would reset pulse_count back to 0 and set another long variable to millis() for example.
const float CIRCUMFERENCE = 3.0F;
const long PULSES_PER_REV = 8;
volatile int pulse_count = 0;
long timems = 0;
// interrupt service routine
void addPulse()
{
pulse_count++;
}
// Returns speed in distance unit per second. So, if circumference was given in meters,
// this would give m/s, and you would multiply it by 3.6 to get speed in km/h and display that.
float speed()
{
//assuming you won't keep the speedometer running for longer than one month in one go.
long time_diff = millis() - timems;
//That's too fast. Not resetting counters before returning so that the next measurement could still succeed.
//This could also return a negative number instead of 0.0F for failed measurements and you could ignore them.
if (time_diff <= 0.0F)
return 0.0F;
float v = CIRCUMFERENCE * pulse_count * 1000.0F / ( time_diff * PULSES_PER_REV );
//reset for next measurement
pulse_count = 0;
timems = millis();
return v;
}
void setup()
{
timems = millis();
attachInterrupt(0, addPulse, RISING);
}
void loop()
{
// call speed() at sensible intervals and update the reading to LCD
...
}
I am assuming that the sensor sets the sensor HIGH based on pulses that occur 8 times per each revolution, so this is something I would start with, and then figure out how to report speed properly in case it gives funky readings in the real world.
Make sure it cannot update speed too often because otherwise this would just report 0 most of the time, because there may not be any pulses since the last measurement. This one includes the interrupt I mentioned earlier, but probably does not give you a stable reading.. So it needs something that calls the function speed() at regular intervals, add delay(1000) or some such. You can tune the delay based on how responsive you want the reading to be, but not too far. I added some safe-guards and comments to try and fix that at the last moment.
You can probably guess the speed from the frequency of the pulses and calibrating the reading to match the actual speed, but this is roughly the same thing and this at least is mathematically correct. The diameter or the circumference of the wheel still directly affects at what rate the pulses would occur, so the circumference and diameter are relevant one way or the other. And of course the air pressure inside the tire affects the pulse rate, and the readings, because the diameter is not always a constant if the tire is filled with air.