Read pulses and Rpm

Hello,

I have a 1 Arduino uno, encoder LM393, servomotor full rotation and one whell atach to servomotor whit 8 holes.

I want to read when the sensor see the holes and increese the numer( 1, 2, 3…etc)
I am stuck in the code
Pls help !!

include<LiquidCrystal.h>
#include <Servo.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 7);
Servo myservo;

int encoder_pin = 2; // pinul unde este conectat ecoderul de la senzor
unsigned int rps; // rpm citire
unsigned int timeold;
volatile byte pulses; // numarul de pulsuri
unsigned int pulsesperturn = 8 ;

void counter()
{
pulses++; // actualizare numaratoare
}

void setup()
{
Serial.begin(9600); // monitorizare calculator

lcd.begin(16, 2); // apelarea LCD-ului care are 16 caractere pe 2 randuri
lcd.print(“SP: 7 (val ok)”);

pinMode(encoder_pin, INPUT);
attachInterrupt(0, counter, FALLING);
pulses=0;
rps=0;
timeold=0;

myservo.attach(9); // pinul 9 de transmitere semnal
myservo.write(20); // setarea vitezei servo motorului
}

void loop()
{
if ( millis()- timeold >= 2000)
{
detachInterrupt(0);
rps = (millis()-timeold)*pulses;
timeold = millis();
pulses=0;

Serial.print(“RPM =”);
Serial.println(rps,DEC);

lcd.setCursor(0,1);
lcd.print(rps);

attachInterrupt(0,counter, FALLING);
}
}

Please use code tags </> to present code.

You seem to have a continuous servo, which you run at speed 20 (whatever that means).

No need to detach/attach the interrupt handler, you simply can turn interrupts off or (better) reset the counter before the next sample. You also should reset timeold just before taking the next sample, or remember the old count and build the difference from the old and new count.

For proper RPM calculation you have to take into account the counts per round (8) and sample time (2000ms).