// Copied from https://wokwi.com/projects/353963309327616001
//
// Changes:
// 1. millis() needs "unsigned long" variables.
// 2. Changed variable names of "t1" and "t1_prev".
// 3. Moved the rpm calculation to the main section of the loop().
// 4. There is no need to use "String", so I replaced those.
// 5. Printing the encoder counter is now after increment or decrement.
// 6. After thinking very hard, I think multiply by 3 is okay.
//
// Notes:
// I don't have a rotary encoder, does 20 steps mean that both the CLK and DT
// have a ring with 10 teeth ?
// I think that "pulse_cnt * 3" is good.
// Do you see how coarse the rpm value changes ? When displaying a low rpm very often,
// it is better to calculate the time between the pulses.
// If you add more code to the sketch, then you might need to start using interrupts.
// The Encoder library is super extra optimized:
// https://www.pjrc.com/teensy/td_libs_Encoder.html
//
#define ENCODER_CLK 2
#define ENCODER_DT 3
// define the pins for the RGB LED
#define LED_RED_PIN 9
#define LED_GREEN_PIN 10
#define LED_BLUE_PIN 11
int lastClk = HIGH;
int pulse_cnt = 0;
unsigned long previousMillis = 0;
unsigned long previousPulseMillis = 0;
void setup() {
Serial.begin(115200);
pinMode(ENCODER_CLK, INPUT);
pinMode(ENCODER_DT, INPUT);
// set the pins for the RGB LED as outputs
pinMode(LED_RED_PIN, OUTPUT);
pinMode(LED_GREEN_PIN, OUTPUT);
pinMode(LED_BLUE_PIN, OUTPUT);
}
void loop() {
unsigned long currentMillis = millis();
int newClk = digitalRead(ENCODER_CLK);
if (newClk != lastClk) {
// There was a change on the CLK pin
lastClk = newClk;
//add to rmp count
pulse_cnt++;
}
// Calculate speed by counting the pulses during a second
if (currentMillis-previousMillis >= 1000) {
// After counting the pulses we have to calculate the speed(revolutions per minute),
// by knowing that KY-040 Rotary Encoder module has 20 steps per revolution.
// We derive the equation: RPM =(counts_second / 20)* 60s = counts_second * 3
int RPM = pulse_cnt * 3;
previousMillis = currentMillis;
pulse_cnt = 0;
Serial.print("RPM = ");
Serial.println(RPM);
if(RPM < 10){
//turn LED red
Serial.print("Speed Up");
setColor(255, 0, 0);
}
else if(RPM > 25){
//turn LED blue
Serial.print("Slow Down");
analogWrite(LED_RED_PIN, 0);
analogWrite(LED_GREEN_PIN, 0);
analogWrite(LED_BLUE_PIN, 255);
}
else{
//turn LED green
Serial.print("All Good");
analogWrite(LED_RED_PIN, 0);
analogWrite(LED_GREEN_PIN, 255);
analogWrite(LED_BLUE_PIN, 0);
}
Serial.print("\n");
}
}
void setColor(int red, int green, int blue)
{
analogWrite(LED_RED_PIN, 255-red);
analogWrite(LED_GREEN_PIN, 255-green);
analogWrite(LED_BLUE_PIN, 255-blue);
}