Have a look at the code in this program that measures the speed and counts the revolutions
const byte fwdPin = 9;
const byte revPin = 10;
const byte potPin = A1;
int potVal;
int pwmVal;
unsigned long revMicros;
unsigned long prevRevMicros;
unsigned long revDuration;
unsigned long revCount;
unsigned long prevDisplayMillis;
unsigned long displayInterval = 1000;
// variables for the ISR
volatile unsigned long isrMicros;
volatile unsigned long isrCount;
volatile bool newIsrMicros = false;
void setup() {
Serial.begin(115200);
Serial.println("SimpleISRdemo.ino");
pinMode (fwdPin, OUTPUT);
pinMode (revPin, OUTPUT);
isrCount = 0;
attachInterrupt(0, revDetectorISR, RISING);
}
//==========
void loop() {
getIsrData();
if (millis() - prevDisplayMillis >= displayInterval) {
prevDisplayMillis += displayInterval;
showData();
readPot();
updateMotorSpeed();
}
}
//===========
void readPot() {
potVal = analogRead(potPin);
}
//===========
void updateMotorSpeed() {
pwmVal = potVal >> 2;
digitalWrite(revPin,LOW);
analogWrite(fwdPin, pwmVal);
}
//===========
void getIsrData() {
if (newIsrMicros == true) {
prevRevMicros = revMicros; // save the previous value
noInterrupts();
revMicros = isrMicros;
revCount = isrCount;
newIsrMicros = false;
interrupts();
revDuration = revMicros - prevRevMicros;
}
}
//===========
void showData() {
Serial.println();
Serial.println("===============");
Serial.print("PWM Val "); Serial.println(pwmVal);
Serial.print(" Rev Duration ");
Serial.print(revDuration);
Serial.print(" Rev Count ");
Serial.print(revCount);
Serial.println();
}
//===========
void revDetectorISR() {
isrMicros = micros();
isrCount ++;
newIsrMicros = true;
}
Among other things note how I am using noInterrupts() rather than detachInterrupt() and that the value of micros() is saved within the ISR to capture it as soon as possible after the pulse is detected. Not also that I never bother to set isrCount back to zero.
...R