Arduino hall effect sensor (rpm) issue

I am trying to code rpm counter and here is the problem i get:

I have attached hall effect sensor to my bicycle and put magnet in the pedals, then i have ran a code to the arduino uno board and opened serial monitor to see the values when riding the bike. Then serial monitor gives inaccurate values such as when riding slow it gives like 100 rpm, then when i increase the speed, it gives sometimes lower values like 40-50. Finally it starts to decrease the values no matter how fast i drive.

Can anyone help me with this issue, i have coded with arduino for only a week so i dont really have that much experience.
Thanks!

Here is my code:

int hallsensor = 2;
volatile byte counter;
unsigned int rpm;
unsigned long passedtime;

void isr()
{
counter++;
}

void setup()
{
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(2), isr, RISING);
pinMode(hallsensor, INPUT);
int counter = 0;
int rpm = 0;
int passedtime = 0;
}

void loop()
{
delay(50);
detachInterrupt(digitalPinToInterrupt(2));
rpm = (301000/(millis() - passedtime) counter);
counter = 0;
Serial.print("RPM=");
Serial.println(rpm);
attachInterrupt(digitalPinToInterrupt(2), isr, RISING);

}

Hi.

I admire your ambition in tackling interrupts after only one week with Arduino.

I tried the interrupt approach on my car speedo using a Hell Effect sensor. It's involved, with issues around measuring time.

I switched to simply polling the pin to detect time elapsed between successive highs. Not difficult and provides accurate consistent readings.

Interrupts are suited to events that can occur at unpredictable moments, like an operator action. The pedal/wheel clicks are quite predictable in their occurrence and happen at a very slow speed from the Arduino's viewpoint.

Good luck.

jpom:
Interrupts are intended for events that can occur at unpredictable moments, like an operator action.

Absolutely NOT! They are not for unpredictable moments but for fast/often happening moments. Depending on the RPM an interrupt sounds good. Although a bike probably will never need that fast but okay.

Some notes:

  • Please use code tags when posting to the forum. Read How to use the forum before making future posts.
  • Don't detach the interrupts, simply disable interrupts. And only for the short amount you work with the variable.
  • And to make to make that time short, just make a local copy of that variable before doing calculations with it
  • 'passedtime' is never updated aka will always stay low...
  • Do you really want to send it to serial every 50ms
  • Er even better, do you even expect 1 or more pulses every 50ms? (Hint, do you go >150kmh?)