#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// OLED display dimensions
#define OLED_WIDTH 128
#define OLED_HEIGHT 32
#define OLED_RESET -1
Adafruit_SSD1306 display(OLED_WIDTH, OLED_HEIGHT, &Wire, OLED_RESET);
// Relay module pins
const int relayPins[] = {2, 3, 4, 5}; // Assign pins for each relay
// Toggle switch pins
const int switchPins[] = {6, 7, 8, 9}; // Assign pins for each toggle switch
// Array to store relay status
bool relayStatus[4] = {false}; // Initialize all relays to OFF
void setup() {
// Initialize serial communication
Serial.begin(9600);
// Initialize OLED display
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
Serial.println(F("SSD1306 allocation failed"));
for(;;);
}
// Clear the display
display.clearDisplay();
display.display();
// Initialize relay pins
for (int i = 0; i < 4; i++) {
pinMode(relayPins[i], OUTPUT);
digitalWrite(relayPins[i], LOW); // Initially turn off all relays
}
// Initialize toggle switch pins
for (int i = 0; i < 4; i++) {
pinMode(switchPins[i], INPUT_PULLUP); // Enable internal pull-up resistors
}
}
void loop() {
// Check each toggle switch
for (int i = 0; i < 4; i++) {
bool currentState = digitalRead(switchPins[i]);
// If toggle switch state changes
if (currentState != relayStatus[i]) {
relayStatus[i] = currentState;
// Update relay state
digitalWrite(relayPins[i], relayStatus[i] ? HIGH : LOW);
// Update OLED display
updateDisplay();
// Small delay to debounce
delay(50);
}
}
}
void updateDisplay() {
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
// Display relay status
for (int i = 0; i < 4; i++) {
display.setCursor(0, i * 8); // Set cursor position for each relay status
display.print("Command ");
display.print(i + 1);
display.print(": ");
display.println(relayStatus[i] ? "ON" : "OFF");
}
// Update OLED display
display.display();
}
Loading
ssd1306
ssd1306