#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 -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
int sensorValue = 0;
int previousPercentage = -1; // To store the previous percentage value
void setup() {
pinMode(A0, INPUT);
// Initialize the SSD1306 display with I2C address 0x3C
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
// Set up the text color
display.setTextColor(SSD1306_WHITE);
// Display startup messages
display.clearDisplay();
// Draw the border around the screen
display.drawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SSD1306_WHITE);
display.setTextSize(3);
display.setCursor((SCREEN_WIDTH - 87) / 2, 7); // Center "System On"
display.println(F("Power"));
display.setTextSize(3);
display.setCursor((SCREEN_WIDTH - 83) / 1, 35);
display.println(F("On"));
display.display();
delay(2000);
display.clearDisplay();
}
void loop() {
// Read the potentiometer value and convert to percentage
sensorValue = analogRead(A0);
int percentage = map(sensorValue, 0, 1023, 0, 100);
// Update the percentage on the OLED only if it has changed
if (percentage != previousPercentage) {
display.clearDisplay();
// Draw the border around the screen
display.drawRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, SSD1306_WHITE);
// Draw a horizontal line between "Master Volume" and the percentage
display.drawLine(0, 18, SCREEN_WIDTH, 18, SSD1306_WHITE);
// Display "Master Volume" at the top
display.setTextSize(1); // Set text size to 1
display.setCursor((SCREEN_WIDTH - 85) / 2, 6); // Center "Master Volume"
display.println(F("Master Volume"));
// Display the percentage in larger text at the bottom
display.setTextSize(4); // Set text size to 4
display.setCursor((SCREEN_WIDTH - 70) / 2, 28); // Center the percentage text at the bottom
display.print(percentage);
display.print(F("%"));
display.display();
previousPercentage = percentage;
}
delay(20); // Short delay to improve response time
}