// Robust Rotary encoder reading // // Copyright John Main - best-microcontroller-projects.com
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Encoder.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
#define CLK 2
#define DATA 3
Encoder encoder(DATA, CLK);
int lastEncoderValue = 0;
int state=0;
int test=0;
int readDelta() {
//int value = encoder.read();
int value = encoder.read() / 4;
int delta = value - lastEncoderValue;
lastEncoderValue = value;
return delta;
}
#define MENU_LENGTH 5
int constrainMenu(int value) {
return value - MENU_LENGTH * floor((float) value / MENU_LENGTH);
}
void setup() {
//pinMode(CLK, INPUT);
//pinMode(CLK, INPUT_PULLUP);
//pinMode(DATA, INPUT);
//pinMode(DATA, INPUT_PULLUP);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.display();
delay(500); // Pause for 4 seconds
Serial.begin(115200);
Serial.println("KY-040 Start:");
}
static uint8_t prevNextCode = 0;
static uint16_t store = 0;
void loop() {
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(5, 12);
display.println(F("Encoder Value:"));
test+=readDelta();
//test=constrainMenu(test+readDelta()); //test menu rotativo
if(test!=state){
Serial.println(test);
state=test;
}
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(90, 8);
display.println(test);
display.display();
/*
static int8_t c, val;
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(5, 12);
display.println(F("Encoder Value:"));
//display.display();
if (val = read_rotary()) {
c += val;
Serial.print(c);
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(90, 8);
display.println(c);
display.display();
Serial.print(" ");
if (prevNextCode == 0x0b) {
Serial.print("eleven ");
Serial.println(store, HEX);
}
if (prevNextCode == 0x07) {
Serial.print("seven ");
Serial.println(store, HEX);
}
}*/
}
// A vald CW or CCW move returns 1, invalid returns 0.
int8_t read_rotary() {
static int8_t rot_enc_table[] = { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 };
prevNextCode <<= 2;
if (digitalRead(DATA)) prevNextCode |= 0x02;
if (digitalRead(CLK)) prevNextCode |= 0x01;
prevNextCode &= 0x0f; // If valid then store as 16 bit data.
if (rot_enc_table[prevNextCode]) {
store <<= 4;
store |= prevNextCode;
//if (store==0xd42b) return 1;
//if (store==0xe817) return -1;
if ((store & 0xff) == 0x2b) return -1;
if ((store & 0xff) == 0x17) return 1;
}
return 0;
}