#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 OLED display
#define OLED_RESET    -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

#define RELAY_PIN 5   // Pin to control relay (LED simulating motor)
#define TEMP_PIN 35   // Analog pin simulating temperature sensor
#define CURRENT_PIN 34 // Analog pin simulating current sensor

int tempThreshold = 500; // Example threshold for simulated temperature (0-1023 range)
int currentThreshold = 500; // Example threshold for simulated current (0-1023 range)

void setup() {
  Serial.begin(115200);
  
  pinMode(RELAY_PIN, OUTPUT);
  digitalWrite(RELAY_PIN, LOW); // Start with motor off
  
  pinMode(TEMP_PIN, INPUT);
  pinMode(CURRENT_PIN, INPUT);

  // Initialize OLED display with I2C address 0x3C for SSD1306
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { 
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  // Clear the buffer
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
}

void loop() {
  // Read simulated temperature from Potentiometer 1
  int tempValue = analogRead(TEMP_PIN);
  // Read simulated current from Potentiometer 2
  int currentValue = analogRead(CURRENT_PIN);
  
  // Display readings in Serial Monitor
  Serial.print("Simulated Temperature Value: ");
  Serial.println(tempValue);  // In real case, you would map this to degrees Celsius
  
  Serial.print("Simulated Current Value: ");
  Serial.println(currentValue);

  // Display on OLED
  display.clearDisplay();
  display.setCursor(0, 0);
  display.print("Temp Value: ");
  display.println(tempValue); // Display temp value
  display.print("Current Value: ");
  display.println(currentValue); // Display current value

  // Check for over-temperature
  if (tempValue > tempThreshold) {
    Serial.println("Over-temperature! Turning motor off...");
    digitalWrite(RELAY_PIN, LOW); // Turn off motor (LED)
    display.println("Over-temp! Motor OFF");
  }
  
  // Check for over-current
  else if (currentValue > currentThreshold) {
    Serial.println("Over-current! Turning motor off...");
    digitalWrite(RELAY_PIN, LOW); // Turn off motor (LED)
    display.println("Over-current! Motor OFF");
  }
  
  // Normal operation (Motor ON if within safe conditions)
  else {
    Serial.println("Motor is running normally...");
    digitalWrite(RELAY_PIN, HIGH); // Turn on motor (LED)
    display.println("Motor is ON");
  }

  display.display(); // Update the OLED display
  delay(2000); // Wait 2 seconds before the next loop
}