I am having difficulty setting up an interrupt to count how many times the magnet passes so that I can count something like every 100 ms the actual speed.
I have a little code put together from the Internet:
const byte LED_pin =13;
const unsigned long wheel_circumference = 431800UL * 2UL * 31416UL; // = 94,248,000
unsigned long Speed = 0;
unsigned long PrevSpeed = 0;
volatile byte hall_rising = 0; // interrupt flag
volatile unsigned long irqMicros;
unsigned long startMicros;
unsigned long elapsedMicros;
unsigned long ledFlashStartMillis;
const unsigned long ledFlashWaitMillis = 10;
unsigned long displayStartMillis;
const unsigned long displayWaitMillis = 100;
void wheel_IRQ()
{
irqMicros = micros();
hall_rising = 1;
}
void setup()
{
pinMode( 2, INPUT_PULLUP ); // pin # is tied to the interrupt
pinMode( LED_pin, OUTPUT );
Serial.begin( 9600 ); // can this be faster? faster would be better
delay( 1000 );
attachInterrupt( 0, wheel_IRQ, RISING ); // pin 2 looks for LOW to HIGH change
}
void loop()
{
if ( hall_rising == 1 )
{
elapsedMicros = irqMicros - startMicros;
startMicros = irqMicros;
hall_rising = 2;
}
else if ( hall_rising == 2 )
{
if ( millis() - ledFlashStartMillis >= ledFlashWaitMillis )
{
hall_rising = 0;
}
}
// print speed 1000/Wait (10) times per second
if ( millis() - displayStartMillis >= displayWaitMillis )
{
Speed = wheel_circumference * 0.0009 / elapsedMicros;
displayStartMillis += displayWaitMillis;
if ( Speed != PrevSpeed )
{
Serial.print(Speed); // this shows mm/sec with no remainder
Serial.println(" kmh");
}
PrevSpeed = Speed;
}
}
But when I use this code in U8glib to display the value on a GLCD . Values are totally wrong. Can someone help me?

count how many times the magnet passes. In your entire code, you never count the number of times the interrupt is fired. You're code assumes that the loop function is called at least as many times as the interrupt is fired. If the loop function takes longer, by e.g. using the GLCD library, multiple interrupts could have fired, leading toelapsedMicrosbeing a multiple of the value you expect. Leading to your code thinking the motor is running at half, or one-third, etc. the speed.