#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
// กำหนดขาต่อ I2C กับจอ OLED
#define OLED_RESET -1 //ขา reset เป็น -1 ถ้าใช้ร่วมกับขา Arduino reset
Adafruit_SSD1306 OLED(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
enum PinAssignments {
encoderPinA = 2,
encoderPinB = 3,
clearButton = 8
};
volatile unsigned int encoderPos = 0;
unsigned int lastReportedPos = 1;
static boolean rotating = false;
boolean A_set = false;
boolean B_set = false;
int run = 0;
void setup() {
Serial.begin(9600);
if (!OLED.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println("SSD1306 allocation failed");
} else {
Serial.println("ArdinoAll OLED Start Work !!!");
}
pinMode(encoderPinA, INPUT_PULLUP);
pinMode(encoderPinB, INPUT_PULLUP);
pinMode(clearButton, INPUT_PULLUP);
attachInterrupt(0, doEncoderA, CHANGE);
attachInterrupt(1, doEncoderB, CHANGE);
}
void loop() {
rotating = true;
if (lastReportedPos != encoderPos) {
Serial.print("Index:");
Serial.println(encoderPos, DEC);
lastReportedPos = encoderPos;
}
if (digitalRead(clearButton) == LOW ) {
encoderPos = 0;
Serial.println("Click:Reset Index");
delay(200);
}
OLED.clearDisplay();
OLED.setTextColor(WHITE, BLACK);
OLED.setCursor(0, 0);
OLED.setTextSize(2);
OLED.drawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, WHITE);
//OLED.setCursor(DEC, SCREEN_HEIGHT/2-8);
//OLED.println(encoderPos, DEC);
OLED.setTextSize(1);
OLED.setCursor(5,0);
OLED.println("DESTINY DEVICE");
OLED.display();
delay(500);
}
// คำสั่งทำงานแบบ interrupt เมื่อมีการหมุน
void doEncoderA() {
// debounce
if ( rotating ) delay (1); // หน่วงเวลาป้องกันสัญญาณบกวน debounce
// เช็คว่ามีบิดสวิตช์
if ( digitalRead(encoderPinA) != A_set ) { // debounce once more
A_set = !A_set;
// adjust counter + if A leads B
if ( A_set && !B_set )
encoderPos += 1;
rotating = false; // no more debouncing until loop() hits again
}
}
// Interrupt on B changing state, same as A above
void doEncoderB() {
if ( rotating ) delay (1);
if ( digitalRead(encoderPinB) != B_set ) {
B_set = !B_set;
// adjust counter - 1 if B leads A
if ( B_set && !A_set )
encoderPos -= 1;
rotating = false;
}
}