#include <Arduino.h>
#include <U8g2lib.h>
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
U8G2_SSD1306_128X64_NONAME_F_HW_I2C u8g2(U8G2_R0, /* reset=*/ U8X8_PIN_NONE);
#define CLK_PIN 2
#define DT_PIN 3
int lastClk = HIGH;
#define DIRECTION_CW 0 // clockwise direction
#define DIRECTION_CCW 1 // counter-clockwise direction
volatile int counter = 0;
volatile int direction = DIRECTION_CW;
volatile unsigned long last_time; // for debouncing
int prev_counter;
int FM = 60;
String Freq="60";
void ISR_encoderChange() {
if ((millis() - last_time) < 50) // debounce time is 50ms
return;
if (digitalRead(DT_PIN) == HIGH) {
// the encoder is rotating in counter-clockwise direction => decrease the counter
counter--;
FM--;
direction = DIRECTION_CCW;
} else {
// the encoder is rotating in clockwise direction => increase the counter
counter++;
FM++;
direction = DIRECTION_CW;
}
last_time = millis();
}
void setup(){
u8g2.begin();
Serial.begin(115200);
pinMode(CLK_PIN, INPUT);
pinMode(DT_PIN, INPUT);
attachInterrupt(digitalPinToInterrupt(CLK_PIN), ISR_encoderChange, RISING);
}
void loop(){
if (prev_counter != counter) {
Serial.print("DIRECTION: ");
if (direction == DIRECTION_CW)
Serial.print("Clockwise");
else
Serial.print("Counter-clockwise");
Serial.print(" | COUNTER: ");
Serial.println(counter);
prev_counter = counter;
}
Freq = String(FM);
u8g2.clearBuffer();
u8g2.setFontMode(1);
u8g2.setBitmapMode(1);
u8g2.setFont(u8g2_font_6x12_tr);
u8g2.drawStr(19, 20, "FM ");
u8g2.drawStr(46, 20, Freq.c_str());
u8g2.drawFrame(7, 24, FM, 3);
u8g2.sendBuffer();
}