#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
#define OLED_RESET 4 // Reset pin # (or -1 if sharing Arduino reset pin)
const int NUM_BTNS = 5;
const int BTN_PINS[] = {12, 11, 10, 9, 8};
int btnState[NUM_BTNS];
int oldBtnState[NUM_BTNS];
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
int checkButtons() {
int btnNumber = 0;
for (int i = 0; i < NUM_BTNS; i++) {
// check each button
btnState[i] = digitalRead(BTN_PINS[i]);
if (btnState[i] != oldBtnState[i]) { // if it changed
oldBtnState[i] = btnState[i]; // remember state for next time
btnNumber = i + 1;
Serial.print("Button ");
Serial.print(btnNumber);
if (btnState[i] == LOW) { // was just pressed
Serial.println(" pressed.");
} else {
btnNumber = -1; // was just released
Serial.println(" released.");
}
delay(20); // debounce
}
}
return btnNumber;
}
void setup() {
Serial.begin(9600);
oled.setRotation(2);
if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;); // halt
}
for (int i = 0; i < NUM_BTNS; i++) {
pinMode(BTN_PINS[i], INPUT_PULLUP);
oldBtnState[i] = HIGH; // pins idle HIGH
}
oled.display();
delay(500);
oled.clearDisplay();
oled.setTextSize(2);
oled.setTextColor(SSD1306_WHITE, SSD1306_BLACK); // draw white on black
oled.setCursor(27, 10);
oled.print("BUTTON:");
oled.display();
}
void loop() {
int button = checkButtons();
if (button > 0) {
oled.setCursor(62, 40);
oled.print(button);
oled.display();
} else if (button == -1) {
oled.setCursor(62, 40);
oled.print(" ");
oled.display();
}
}