#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
// OLED Display Configuration
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
// Pin Definitions for ESP32
const int RELAY_PINS[4] = {16, 17, 18, 19}; // 4 Relay Channels
const int SENSOR_PINS[4] = {34, 35, 32, 33}; // 4 Sensor/Switch Inputs
// State Tracking
bool relayState[4] = {false, false, false, false};
int sensorValues[4] = {0, 0, 0, 0};
void setup() {
Serial.begin(115200);
// Initialize Relay Pins
for (int i = 0; i < 4; i++) {
pinMode(RELAY_PINS[i], OUTPUT);
digitalWrite(RELAY_PINS[i], LOW); // Set initial state
}
// Initialize Sensor Pins
for (int i = 0; i < 4; i++) {
pinMode(SENSOR_PINS[i], INPUT_PULLUP);
}
// Initialize OLED
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for(;;); // Don't proceed, loop forever
}
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
// ESP32 Specific Configurations
analogReadResolution(10);
analogSetAttenuation(ADC_11db);
}
void updateDisplay() {
display.clearDisplay();
display.setTextSize(1);
// Header
display.setCursor(0, 0);
display.println("IN / OUT Status");
display.drawFastHLine(0, 10, SCREEN_WIDTH, SSD1306_WHITE);
// Side-by-Side Layout
// Inputs on Left (Column 1)
display.setCursor(0, 12);
display.print("I:");
for (int i = 0; i < 4; i++) {
display.setCursor(0, 20 + (i * 10));
display.print("S");
display.print(i+1);
display.print(":");
display.print(sensorValues[i]);
}
// Outputs on Right (Column 2)
display.setCursor(64, 12);
display.print("O:");
for (int i = 0; i < 4; i++) {
display.setCursor(64, 20 + (i * 10));
display.print("R");
display.print(i+1);
display.print(":");
display.print(relayState[i] ? "ON " : "OFF");
}
// Vertical Separator Line
display.drawFastVLine(62, 12, 52, SSD1306_WHITE);
display.display();
}
void checkSensors() {
// Read analog and digital sensor values
sensorValues[0] = analogRead(SENSOR_PINS[0]); // Analog input
// Digital inputs
for (int i = 1; i < 4; i++) {
sensorValues[i] = digitalRead(SENSOR_PINS[i]);
}
}
void toggleRelay(int relayNum) {
if (relayNum >= 0 && relayNum < 4) {
relayState[relayNum] = !relayState[relayNum];
digitalWrite(RELAY_PINS[relayNum], relayState[relayNum]);
}
}
void loop() {
// Read sensor states
checkSensors();
// Example: Toggle relays based on sensor inputs
for (int i = 1; i < 4; i++) {
if (sensorValues[i] == LOW) {
toggleRelay(i-1);
delay(200); // Debounce
}
}
// Update display
updateDisplay();
// Small delay to prevent flickering
delay(100);
}