Counter increasing more than once inside an interrupt (Servo.h and MsTime2.h)

I'm using an Arduino Uno and I'd like to measure the rpm of a motor with an optocoupler (LM393).

I included the MsTimer2.h and the Servo.h libraries.

When I run my program I read in my serial monitor that the counter increases more than once per a revolution, when it shouldn't.

#include <MsTimer2.h>
#include <Servo.h>
volatile byte counter=0;
Servo myservo;
int val;  
int pin=13;
volatile byte output=LOW;

void docount(){  // counts from the speed sensor
  volatile byte output = HIGH;
  digitalWrite(pin, output); 
  output = !output;
  counter++;  // increase +1 the counter value
  Serial.println(counter,DEC);
} 

void timerIsr() {
  MsTimer2::stop(); // stop the timer
  int rotation = (counter*60);  // divide by number of holes in Disc
 Serial.println(rotation,DEC);  
  counter=0;  //  reset counter to zero
  MsTimer2::start();  //enable the timer
}

void setup() {
  Serial.begin(9600); 
  myservo.attach(9); 
  pinMode(pin, OUTPUT);
  MsTimer2::set(1000,timerIsr); // set timer for 1 sec
  attachInterrupt(0, docount, RISING); // increase counter when speed sensor pin goes High
  MsTimer2::start();// enable the timer
}

void loop() {
  digitalWrite(pin, output);
  //Serial.println(counter,DEC); 
  val = analogRead(1);            // reads the value of the potentiometer (value between 0 and 1023)
  val = map(val, 0, 1023, 94, 142);     // scale it to use it with the servo (value between 0 and 180)
  myservo.write(val);                  // sets the servo position according to the scaled value
}

Could somebody please tell me where am I wrong?

Many thanks,
Andrea

The low cost lm393 modules can bounce in the digital mode. There is no hysteresis control in the comparator circuit.

A simple solution appears to be a capacitor across the digital output and ground.

See this thread for a discussion of the problem.

https://forum.arduino.cc/index.php?topic=342650.0

Here's some detail on the simple capacitor solution

Thanks for your kind reply and the useful information Cattledog. The capacitor was more than enough :slight_smile: