//oled
#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)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
//encoder
#define ENC_A 2
#define ENC_B 3
#define encoder0Btn 4
const unsigned long eventInterval = 1000;
unsigned long previousTime = 0;
unsigned long _lastIncReadTime = micros();
unsigned long _lastDecReadTime = micros();
int _pauseLength = 25000;
int _fastIncrement = 10;
volatile int counter = 0;
int x=0;
//encoder
void setup(){
Serial.begin(9600);
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
// Set encoder pins and attach interrupts
pinMode(ENC_A, INPUT_PULLUP);
pinMode(ENC_B, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(ENC_A), read_encoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(ENC_B), read_encoder, CHANGE);
pinMode(encoder0Btn, INPUT_PULLUP);
}
void loop(){
unsigned long currentTime = millis();
/* This is the event */
if (currentTime - previousTime >= eventInterval) {
/* Event code */
int btn = digitalRead(encoder0Btn);
if(btn==1){
Serial.println("button on ");
Serial.println(x);
}
else{
Serial.println("button off ");
x=x+1;
Serial.println(x);
if(x>=4){
x=0;
}
}
/* Update the timing for the next time around */
previousTime = currentTime;
}
static int lastCounter = 0;
// If count has changed print the new value to serial
if(counter != lastCounter){
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(WHITE);
display.setCursor(0, 0);
display.println("Encoder rotation ");
display.print(counter);
lastCounter = counter;
display.display();
}
}
void read_encoder() {
// Encoder interrupt routine for both pins. Updates counter
// if they are valid and have rotated a full indent
static uint8_t old_AB = 3; // Lookup table index
static int8_t encval = 0; // Encoder value
static const int8_t enc_states[] = {0,-1,1,0,1,0,0,-1,-1,0,0,1,0,1,-1,0}; // Lookup table
old_AB <<=2; // Remember previous state
if (digitalRead(ENC_A)) old_AB |= 0x02; // Add current state of pin A
if (digitalRead(ENC_B)) old_AB |= 0x01; // Add current state of pin B
encval += enc_states[( old_AB & 0x0f )];
// Update counter if encoder has rotated a full indent, that is at least 4 steps
if( encval > 3 ) { // Four steps forward
int changevalue = 1;
if((micros() - _lastIncReadTime) < _pauseLength) {
changevalue = _fastIncrement * changevalue;
}
_lastIncReadTime = micros();
counter = counter + changevalue; // Update counter
encval = 0;
}
else if( encval < -3 ) { // Four steps backward
int changevalue = -1;
if((micros() - _lastDecReadTime) < _pauseLength) {
changevalue = _fastIncrement * changevalue;
}
_lastDecReadTime = micros();
counter = counter + changevalue; // Update counter
encval = 0;
}
}