#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET    -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// Relay pins
const int line1RelayPin = 19;
const int line2RelayPin = 4;
const int line3RelayPin = 18;

// Analog pin for measuring voltage (resistance simulation)
const int voltagePin = 34;

// Variables to store the measured voltage and calculated resistance
int measuredVoltage = 0;
int calculatedResistance = 0;

// Function to initialize OLED display
void initializeDisplay() {
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;);
  }
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.println(F("Underground Cable Fault Detector"));
  display.display();
  delay(2000);
}

// Function to read analog pin, print, and display on OLED
void readAndDisplay(const char* line) {
  measuredVoltage = analogRead(voltagePin);
  calculatedResistance = map(measuredVoltage, 0, 4095, 0, 5000); // Assuming 5k as max resistance

  // Print to serial monitor
  Serial.print(line);
  Serial.print(" - Voltage: ");
  Serial.println(measuredVoltage);
  // Serial.print(", Resistance: ");
  // Serial.println(calculatedResistance);

  // Display on OLED
  display.clearDisplay();
  display.setCursor(0, 0);
  display.setTextSize(1);
  display.print("Line: ");
  display.println(line);
  display.print("Voltage: ");
  display.println(measuredVoltage);
  display.print("Resistance: ");
  display.print(calculatedResistance);
  display.println(" ohms");
  display.display();
}

void setup() {
  Serial.begin(115200);
  
  // Initialize OLED display
  initializeDisplay();
  
  // Set relay pins as output
  pinMode(line1RelayPin, OUTPUT);
  pinMode(line2RelayPin, OUTPUT);
  pinMode(line3RelayPin, OUTPUT);

  // Set relay pins to HIGH (inactive)
  digitalWrite(line1RelayPin, LOW);
  digitalWrite(line2RelayPin, LOW);
  digitalWrite(line3RelayPin, LOW);

  // Display initial message
  display.clearDisplay();
  display.setCursor(0, 0);
  display.println(F("System Ready"));
  display.display();
  delay(2000);
}

void loop() {
  // Relay 1 HIGH, read and display
  digitalWrite(line1RelayPin, HIGH);
  readAndDisplay("Line 1");
  // digitalWrite(line1RelayPin, LOW);
  delay(2000);

  // // Relay 2 HIGH, read and display
  // digitalWrite(line2RelayPin, HIGH);
  // readAndDisplay("Line 2");
  // digitalWrite(line2RelayPin, LOW);
  // delay(2000);

  // // Relay 3 HIGH, read and display
  // digitalWrite(line3RelayPin, HIGH);
  // readAndDisplay("Line 3");
  // // digitalWrite(line3RelayPin, LOW);
  // delay(2000);

  // Small delay before repeating
  delay(1000);
}
NOCOMNCVCCGNDINLED1PWRRelay Module
NOCOMNCVCCGNDINLED1PWRRelay Module
NOCOMNCVCCGNDINLED1PWRRelay Module