#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
// Declaration for SSD1306 display connected using I2C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
const int buttonPower = 10; // Pin for Power On/Off button
bool isPoweredOn = false; // Variable to track the power state
bool lastButtonState = HIGH; // Store the last button state
void setup() {
// Initialize the OLED display
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
// Set the button pin as input with internal pull-up resistor
pinMode(buttonPower, INPUT_PULLUP);
// Clear the display at the start
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
}
void loop() {
// Read the current state of the button
bool currentButtonState = digitalRead(buttonPower);
// Check if the button state has changed from HIGH to LOW (button press)
if (currentButtonState == LOW && lastButtonState == HIGH) {
delay(50); // Debounce delay
// Toggle the power state
isPoweredOn = !isPoweredOn;
if (isPoweredOn) {
// Display "System Powered On" when powered on
display.clearDisplay();
display.setCursor(0, 0);
display.println(F("System Powered On"));
display.display();
} else {
// Clear the display when powered off
display.clearDisplay();
display.display();
}
}
// Save the current button state for the next loop iteration
lastButtonState = currentButtonState;
}
Loading
ssd1306
ssd1306