I'm trying to find The RPM of a fan, so I removed one blade from the fan and put an IR sensor in front of it, so when the fan complete a spin the sensor will return a pulse, Here is the code I'm using:
#define PWM 9
#define DINS 2
volatile int counter = 0;
int delaycounter = 0;
int lastcount = 0;
int newcount = 0;
int countCounter = 0;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(PWM, OUTPUT);
pinMode(DINS, INPUT);
attachInterrupt(digitalPinToInterrupt(DINS), readEncoder, RISING);
}
void loop() {
// put your main code here, to run repeatedly:
analogWrite(PWM,50);
int value = digitalRead(DINS);
if (delaycounter == 1000){
lastcount = counter;
newcount = (newcount + counter) / 2;
//Serial.print(counter);
counter = 0;
delaycounter = 0;
countCounter++;
}else{
lastcount = 0;
}
delaycounter = delaycounter + 2 ;
//Serial.print(delaycounter);
//Serial.print(" ");
Serial.print(value);
Serial.print(" ");
Serial.print(counter/2);
Serial.print(" ");
//Serial.print(lastcount);
//Serial.print(" ");
//Serial.print(newcount);
Serial.println();
delay(2);
}
void readEncoder(){
counter++;
}
The problem is the counter in the ISR in counting more than the number of RISING edges,I just want the counter value to increase by one, but instead it increase multiple times even at the FALLING edge of the pulse, like in this Serial plotter:
I tried other solutions like using millis()
and a last_time
variable to track the time to reset the counter but sill the results were the same.
Edit1:
I have opened Serial Monitor and here are the vales it reads, it's adding by 1 or by 2 randomly on the FALLING edge while it should only count ones and in the RISING edge:
DINS
signal on a scope?