//Connection between ESP32 and OLED
// 3.3V ------Vcc
// GND ------GND
// GPIO22 ----- SCL
// GPIO21 ----- SDA

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define I2C_SDA 6
#define I2C_SCL 7

#define ENCODER_CLK 10
#define ENCODER_DT  11
#define ENCODER_BTN 23

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels

int counter = 0;
int state = 0;

void IRAM_ATTR readEncoder() {
  int dtValue = digitalRead(ENCODER_DT);
  if (dtValue == HIGH) {
    counter++; // Clockwise
    state = 1;
  }
  if (dtValue == LOW) {
    counter--; // Counterclockwise

    state = 1;
  }
}

// Get the counter value, disabling interrupts.
// This make sure readEncoder() doesn't change the value
// while we're reading it.
int getCounter() {
  int result;
  noInterrupts();
  result = counter;
  interrupts();
  return result;
}

void resetCounter() {
  noInterrupts();
  counter = 0;
  interrupts();
}

//TwoWire I2CBME = TwoWire(0);

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);

void setup() {
  Serial.begin(115200);

  //I2CBME.begin(I2C_SDA, I2C_SCL, 100000);
  //status = bme.begin(0x76, &I2CBME);  

  //Wire.setpins(I2C_SDA, I2C_SCL);
  Wire.begin(I2C_SDA, I2C_SCL);

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3D for 128x64
    Serial.println(F("SSD1306 allocation failed"));
    for(;;);
  }
  delay(2000);
  display.clearDisplay();

  display.setTextSize(2);
  display.setTextColor(WHITE);
  display.setCursor(0, 5);
  // Display static text
  display.println("Hello, KLU !");
  display.display(); 

  pinMode(ENCODER_CLK, INPUT);
  pinMode(ENCODER_DT, INPUT);

  pinMode(ENCODER_BTN, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);

  attachInterrupt(digitalPinToInterrupt(ENCODER_CLK), readEncoder, FALLING);
}

void loop() {
  //-- Update counter on OLED
  if (state == 1){
    state = 0;
    
    display.clearDisplay();

    display.setTextSize(5);
    display.setTextColor(WHITE);
    display.setCursor(0, 10);
    // Display static text
    display.println(counter);
    display.display(); 
  }

  //-- Clear counter when press button :
  if (digitalRead(ENCODER_BTN) == LOW) {
    resetCounter();
    display.clearDisplay();

    display.setTextSize(5);
    display.setTextColor(WHITE);
    display.setCursor(0, 10);
    // Display static text
    display.println(counter);
    display.display(); 
  }


  // put your main code here, to run repeatedly:
  //delay(10); // this speeds up the simulation
}
esp:0
esp:1
esp:2
esp:3
esp:4
esp:5
esp:6
esp:7
esp:8
esp:9
esp:10
esp:11
esp:12
esp:13
esp:15
esp:18
esp:19
esp:20
esp:21
esp:22
esp:23
esp:3V3
esp:RST
esp:5V
esp:GND.1
esp:NC0
esp:NC1
esp:GND.2
esp:GND.3
esp:RX
esp:TX
esp:GND.4
Loading
ssd1306
encoder1:CLK
encoder1:DT
encoder1:SW
encoder1:VCC
encoder1:GND