#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define TEXT_1_WIDTH 21
#define TEXT_1_HEIGHT 8
#define OLED_RESET -1
#define SCREEN_ADDRESS 0x3C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
int buttonPin[] = {2, 3, 4, 5, 7, 8}; // button array
const int buttons = sizeof(buttonPin) / sizeof(buttonPin[0]); // number of buttons
unsigned long timer[buttons], timeout[buttons]; // debounce array
bool currentButtonState[buttons], lastButtonRead[buttons], currentButtonRead[buttons]; // state array
int buttonCount[buttons];
void setup() {
Serial.begin(115200);
display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS);
display.clearDisplay(); // clear OLED buffer
display.display(); // show cleared buffer
for (int i = 0; i < buttons; i++) { // configure buttons
pinMode(buttonPin[i], INPUT_PULLUP); // pin to button (n.o.), button to gnd
timeout[i] = 50; // debounce timeout
}
// oledText();
// delay(1000);
// oledBox();
}
void loop() {
for (int i = 0; i < buttons; i++) {
readButton(i);
}
}
void oledBox() {
display.drawRect(0, 0, SCREEN_WIDTH - 1, SCREEN_HEIGHT - 1, 1);
display.display();
}
void oledText() {
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 0);
for (int j = 0; j < TEXT_1_HEIGHT; j++) {
for (int i = 0; i < TEXT_1_WIDTH; i++) {
display.print("X");
}
display.println();
}
display.display();
}
void readButton(int buttonpin) {
currentButtonRead[buttonpin] = digitalRead(buttonPin[buttonpin]); // read button pin
if (currentButtonRead[buttonpin] != lastButtonRead[buttonpin]) { // if button pin changes...
timer[buttonpin] = millis(); // ...start a timer
lastButtonRead[buttonpin] = currentButtonRead[buttonpin]; // ... and store current state
}
if ((millis() - timer[buttonpin]) > timeout[buttonpin]) { // if button change was longer than debounce timeout
if (currentButtonState[buttonpin] == HIGH && lastButtonRead[buttonpin] == LOW) { // ... and State is "NOT pressed" while Button "IS PRESSED"
//==================================================
digitalWrite(LED_BUILTIN, HIGH); // The button was pressed...
showButton(buttonPin[buttonpin], ++buttonCount[buttonpin]); // Put actions or function calls here
digitalWrite(LED_BUILTIN, LOW);
//==================================================
}
currentButtonState[buttonpin] = currentButtonRead[buttonpin]; // update button state
}
}
void showButton(int button, unsigned long count) {
Serial.print("Button (count) ");
for (int i = 0; i < buttons; i++) {
Serial.print(i);
Serial.print("(");
Serial.print(buttonCount[i]); // print button press count
Serial.print(") ");
}
Serial.println();
}
UP
DOWN
LEFT
RIGHT
BACK
SELECT