#include <Arduino.h>
// Define the pin connected to the encoder
const int encoderPin = 2; // Using digital pin 2 for the encoder input
volatile int pulseCount = 0; // This variable will increase in the ISR
// PWM output pin
const int pwmPin = 9; // Using digital pin 9 for PWM output
// Time tracking
unsigned long lastTime = 0;
unsigned long currentTime = 0;
void setup() {
// Initialize the encoder pin as an input
pinMode(encoderPin, INPUT);
attachInterrupt(digitalPinToInterrupt(encoderPin), countPulse, RISING); // Trigger on rising edge
// Initialize the PWM output pin
pinMode(pwmPin, OUTPUT);
// Setup serial communication
Serial.begin(9600);
}
void loop() {
currentTime = millis();
if (currentTime - lastTime >= 1000) { // Calculate rate every second
int rate = pulseCount; // Pulses per second
// Map the pulse rate to PWM output
int pwmValue = map(rate, 5, 100, 64, 255); // Mapping 5 pulses/sec to 25% (64/255) and 100 pulses/sec to 100% (255/255)
analogWrite(pwmPin, pwmValue);
// Output rate and PWM for monitoring
Serial.print("Rate: ");
Serial.print(rate);
Serial.print(" pulses/sec, PWM: ");
Serial.println(pwmValue);
// Reset pulse count and lastTime for the next second
pulseCount = 0;
lastTime = currentTime;
}
}
void countPulse() {
pulseCount++;
}