I'm trying to measure speed of a fly wheel with a reed switch with one magnet (1 pulse per full rotation). I have an 100nf cap connected to switch to help with debounce.
#include <Arduino.h>
int speedPin = 2; // switch is connected to pin 2
int ledPin = 13;
int debounceTime = 7;
long speedPulseTime = 0;
int speedPulseCount = 0;
int speed = 0;
long speedLastSample = 0;
long serialLastReport = 0;
int serialReportFreq = 40;
void speedPulse()
{
long time = millis();
if ((speedPulseTime + debounceTime) < time)
{
speedPulseCount++;
speedPulseTime = time;
}
}
void setup()
{
pinMode(ledPin, OUTPUT);
pinMode(speedPin, INPUT_PULLUP); // Set the switch pin as input
attachInterrupt(digitalPinToInterrupt(speedPin), speedPulse, HIGH);
Serial.begin(115200);
Serial.println("Ready...");
}
void loop()
{
long time = micros();
if (speedPulseCount >= 4 || (speedLastSample + 1500000) < time)
{
detachInterrupt(speedPin);
int tempSpeed = 1000000 / ((time - speedLastSample) / speedPulseCount);
if (tempSpeed < 0)
{
speed = 0;
}
else
{
speed = tempSpeed;
}
//reset sample
speedLastSample = time;
speedPulseCount = 0;
attachInterrupt(digitalPinToInterrupt(speedPin), speedPulse, HIGH);
}
if ((serialLastReport + serialReportFreq) < millis())
{
Serial.print(millis());
Serial.print(",");
Serial.println(speed);
serialLastReport = millis();
}
}
Here the code I have so far. The problem I have it jumps around a little bit. What could I change to ensure more accurate readings?