#define PPR 20 // Impulsi per rotazione del KY-040
unsigned long lastTime = 0;
volatile long pulseCount = 0;
void IRAM_ATTR countPulse() {
pulseCount++;
}
void setup() {
Serial.begin(115200);
attachInterrupt(digitalPinToInterrupt(2), countPulse, RISING);
lastTime = millis();
}
void loop() {
unsigned long now = millis();
unsigned long timeInterval = now - lastTime;
if (timeInterval >= 1000) {
noInterrupts();
long currentPulseCount = pulseCount;
pulseCount = 0;
interrupts();
float rpm = (currentPulseCount * 60000.0) / (timeInterval * PPR);
Serial.print("Velocità: ");
Serial.print(rpm);
Serial.println(" RPM");
lastTime = now;
}
delay(10);
}