#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Arduino and KY-040 module
//--https://www.phippselectronics.com/using-the-rotary-encoder-module-ky-040-with-arduino/
int encoderPinA = 8; // CLK pin
int encoderPinB = 9; // DT pin
int encoderBtn = 10; // SW pin
int count = 0;
int encoderPinA_prev;
int encoderPinA_value;
boolean bool_CW;
void setup() {
Serial.begin (9600);
// SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3D)) { // Address 0x3D for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
// Show initial display buffer contents on the screen --
// the library initializes this with an Adafruit splash screen.
display.display();
delay(2000); // Pause for 2 seconds
// Clear the buffer
display.clearDisplay();
pinMode (encoderPinA, INPUT);
pinMode (encoderPinB, INPUT);
pinMode(encoderBtn, INPUT_PULLUP);
encoderPinA_prev = digitalRead(encoderPinA);
}
void loop() {
encoderPinA_value = digitalRead(encoderPinA);
if (encoderPinA_value != encoderPinA_prev) { // check if knob is rotating
// if pin A state changed before pin B, rotation is clockwise
if (digitalRead(encoderPinB) != encoderPinA_value) {
count ++;
bool_CW = true;
} else {
// if pin B state changed before pin A, rotation is counter-clockwise
bool_CW = false;
count--;
}
if (bool_CW) {
Serial.print("Clockwise | ");
} else {
Serial.print("Counter-Clockwise | ");
}
Serial.print(count);
Serial.print(" | ");
}
encoderPinA_prev = encoderPinA_value;
// check if button is pressed (pin SW)
if (digitalRead(encoderBtn) == LOW) Serial.println("Button Pressed");
}
//else Serial.println("Button Released");
//}