#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();
delay(1000);
display.clearDisplay();
display.setCursor((128 - 13 * 6) / 2, (64 - 5) / 2); // center/middle text
display.print("Press a button.");
display.display();
}
int thebutton;
void loop() {
for (int i = 0; i < buttons; i++) {
readButton(i);
}
if (thebutton) {
Serial.print(thebutton);
thebutton = 0;
}
}
void readButton(int readPin) {
currentButtonRead[readPin] = digitalRead(buttonPin[readPin]); // read button pin
if (currentButtonRead[readPin] != lastButtonRead[readPin]) { // if button pin changes...
timer[readPin] = millis(); // ...start a timer
lastButtonRead[readPin] = currentButtonRead[readPin]; // ... and store current state
}
if ((millis() - timer[readPin]) > timeout[readPin]) { // if button change was longer than debounce timeout
if (currentButtonState[readPin] == HIGH && lastButtonRead[readPin] == LOW) { // ... and State is "NOT pressed" while Button "IS PRESSED"
//==================================================
// a button was pressed, use commands or functions
digitalWrite(LED_BUILTIN, HIGH);
thebutton = buttonPin[readPin];
showButton(++buttonCount[readPin]); // Count the button[pin]
digitalWrite(LED_BUILTIN, LOW);
//==================================================
}
currentButtonState[readPin] = currentButtonRead[readPin]; // update button state
}
}
void showButton(unsigned long count) {
Serial.print("Button (count): ");
for (int i = 0; i < buttons; i++) {
Serial.print(buttonPin[i]); // pin number
Serial.print("(");
Serial.print(buttonCount[i]); // button presses
Serial.print(") ");
}
Serial.println();
}
void oledBox() {
display.drawRect(0, 0, SCREEN_WIDTH - 1, SCREEN_HEIGHT - 1, WHITE);
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();
}
UP
DOWN
Loading
ssd1306
ssd1306
LEFT
RIGHT
BACK
SELECT