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

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

// Pins for sensors
int solarVoltagePin = A0;  // Pin for solar voltage
int batteryVoltagePin = A1; // Pin for battery voltage
int solarCurrentPin = A2;  // Pin for solar current (ACS712 or INA219)
int batteryCurrentPin = A3; // Pin for battery current
int outputPin = A4;  // Pin for output load measurement

float solarVoltage = 0.0, batteryVoltage = 0.0;
float solarCurrent = 0.0, batteryCurrent = 0.0;
float outputVoltage = 0.0, outputCurrent = 0.0;
float solarPower = 0.0, batteryPower = 0.0, outputPower = 0.0;

void setup() {
  Serial.begin(9600);

  // Initialize OLED display
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;);
  }
  display.clearDisplay();
  
  // Display initialization message
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0,0);
  display.println("NIVAN TECH");
  display.display();
  delay(2000);
}

void loop() {
  // Read solar voltage and current
  solarVoltage = analogRead(solarVoltagePin) * (5.0 / 1023.0) * 11;  // Assuming a 1:10 voltage divider
  solarCurrent = analogRead(solarCurrentPin) * (5.0 / 1023.0) - 2.5; // Adjust for ACS712 0A offset
  
  // Read battery voltage and current
  batteryVoltage = analogRead(batteryVoltagePin) * (5.0 / 1023.0) * 11;
  batteryCurrent = analogRead(batteryCurrentPin) * (5.0 / 1023.0) - 2.5;

  // Calculate power for solar and battery
  solarPower = solarVoltage * solarCurrent;
  batteryPower = batteryVoltage * batteryCurrent;

  // Read output voltage and current (same principle)
  outputVoltage = analogRead(outputPin) * (5.0 / 1023.0) * 11;
  outputCurrent = analogRead(outputPin) * (5.0 / 1023.0) - 2.5;
  outputPower = outputVoltage * outputCurrent;

  // Display on OLED
  display.clearDisplay();
  
  // Solar data
  display.setCursor(0, 0);
  display.print("Solar-");
  display.print("V: "); display.print(solarVoltage); display.println("V");
  display.print("I:"); display.print(solarCurrent); display.print("A");
  display.print("  P:"); display.print(solarPower); display.print("W");

  // Battery data
  display.setCursor(0, 18);
  display.print("B-");
  display.print("V: "); display.print(batteryVoltage); display.println("V");
  display.print("I: "); display.print(batteryCurrent); display.print("A");
  display.print("P: "); display.print(batteryPower); display.println("W");

  // Output data
  display.setCursor(0, 35);
  display.print("Out V: "); display.print(outputVoltage); display.println("V");
  display.print("Out P: "); display.print(outputPower); display.println("W");
  
  display.setCursor(40,55);
  display.println("NIVAN TECH");
  display.display();
  
  delay(1000);  // Update every second
}