Interrupts on Uno and Mega2560 for Hall Effect Tacho

Hi, First of all I'm sorry that my first post is a cry for help - I generally persevere until I find a solution but this is driving me nuts. I'm a copy, paste, investigate and customise kind of learner.

So I have both a Uno and a Mega 2560 - I'm trying to build a hall effect tacho for my motorbike. I believe interrupts are the way forward.

For smoothing I would like to use a period of say 2 seconds to count the pulses from my sensor and then update the display. I'm using 5 seconds during testing as its easier to manually input pulses using a switch or, to test the hall effect, a magnet.

Here's my code:

volatile byte counter;

void Interrupt_Function()
 {
      counter++;
 }

void setup()
 {
  Serial.begin(9600);
   attachInterrupt(0, Interrupt_Function, RISING);
   pinMode(2, INPUT);
   counter = 0;
 }

void loop()
 {
   delay(5000);
   detachInterrupt(0);   

   Serial.print("Counter = ");
   Serial.println(counter);
   counter = 0;
   attachInterrupt(0, Interrupt_Function, RISING);
  }

So I have two issues. The first is a difference between Uno and Mega2560.

On the Uno, my serial monitor respects my delay(5000; come what may - the serial monitor only updates every 5000ms. On the Mega, every time I use the switch and create my pulse, firing the interrupt, the serial monitor prints. Which is not what I expected, and is different between boards.

My second, and frankly main problem, is that my counter is not incrementing by one each time I flick the switch or pass a magnet by my hall effect sensor.

Instead, I get a range of numbers from (typically) 8x, to 2xx to 16,xxx to 32,xxx (and all numbers in between. Even if I create one pulse, it's as if the Arduino is creating a pulse for every cycle of the processor instead of every cycle of my switch or pass of the magnet.

I have no oscilloscope so I'm unable to judge how much interference is occurring so it's 'possible' it could be along those lines.

In a simpler code though, just printing the digital input, with the magnet or the switch I get very clean 1s and 0s as expected per actuation of the switch.

I expected to be able to set a period of 5secs, pass my magnet in front of the sensor, say twice, within that five seconds and then have the next println of counter to say 2.

But on the Uno it will say any of those random numbers. On the Mega I get the random numbers but printed every time I create a pulse instead of every 5 secs.

Thanks, Morgan

Update: for the pulses I'm going to try Debouncing. This will not affect the Uno vs. Mega differences though.

So debouncing, or adding an anti-repeat time comparison seems to have had an effect ( if (interrupt_time - last_interrupt_time > 20) ).

However, the Mega still implements the code in my loop() every time it receives a pulse instead of every five seconds as planned.