#include <LiquidCrystal_I2C.h>
#define ENCODER_CLK 2
#define ENCODER_DT 3
LiquidCrystal_I2C lcd(0x27, 16, 2); // LCD format: (I2C address, columns, rows)
int encoder0Pos = 0; // Encoder Position variable
float actualtime = 0; // Current time
float previoustime = 0; // The last time we incremented the RPS
const int interval = 1000; // Interval of 1 s
int RPS = 0;
volatile bool flag = false; // need volatile descriptor due to sharing with interrupt function
void setup() {
lcd.init(); // LCD start-up
lcd.setCursor(2, 0);
lcd.print("Iniciating");
lcd.setCursor(0, 1);
lcd.print("Encoder V04");
delay(2000);
lcd.clear();
pinMode(ENCODER_DT, INPUT);
pinMode(ENCODER_CLK, INPUT);
attachInterrupt(digitalPinToInterrupt(2), counters, RISING); // Configure interrupt only for ENCODER_CLK
Serial.begin(115200); // Serial port start-up
}
void loop() {
actualtime = millis(); // Start of the timer
if (flag == true) {
lcd.setCursor(1, 1); // Signaling
lcd.print(encoder0Pos);
lcd.print(" encoder0Pos ");
Serial.print(encoder0Pos);
Serial.print("/");
flag = false;
}
if (actualtime - previoustime >= interval) {
lcd.setCursor(2, 2); // Signaling
lcd.print(RPS);
lcd.print(" RPS");
Serial.print(RPS);
Serial.print("/");
previoustime = actualtime;
}
}
void counters() {
flag = true;
int dtValue = digitalRead(ENCODER_DT);
if (dtValue == LOW) {
encoder0Pos++; // Sens horaire
}
if (dtValue == HIGH) {
encoder0Pos--; // Sens antihoraire
}
if (encoder0Pos == 24) {
RPS++;
encoder0Pos = 0;
}
}