#include <SPI.h>

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
constexpr uint8_t Sync = 2;
constexpr uint8_t Led_Rosso = 8;
constexpr uint8_t Led_Verde = 9;
int sensorValue;
int cyccnt = 0;
byte stcur = 1;
int Volt_pin = A0;
int MaxVolt = 0;
long MedVolt = 0;
int DeVolt;
double Volt;
int Amp1_pin = A1; // potenza prodotta
int MinAmp1 = 1023;
int MaxAmp1 = 0;
int DeAmp1;
long MedAmp1 = 0;
double Amp1 = 0;
unsigned int WattSec1;
byte MaxVerso1;
byte AMax1 = 0;
int Amp2_pin=A2; // potenza consumata
int MinAmp2 = 1023;
int MaxAmp2 = 0;
int DeAmp2;
long MedAmp2 = 0;
double Amp2 = 0;
unsigned int WattSec2;
long WattMin2 = 0;
byte MaxVerso2;
byte AMax2 = 0;
void setup()
{
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextSize(2);
display.setTextColor(WHITE);
pinMode(Sync, INPUT);
pinMode(Led_Rosso, OUTPUT);
pinMode(Led_Verde, OUTPUT);
digitalWrite(Led_Rosso, HIGH);
digitalWrite(Led_Verde, HIGH);
while(digitalRead(Sync) == LOW){
}
}
void loop()
{
if(stcur == 0){
if (digitalRead(Sync) == HIGH){
stcur = 1;
cyccnt = cyccnt + 1;
DeVolt = MaxVolt;
DeAmp1 = MaxAmp1 - MinAmp1;
DeAmp2 = MaxAmp2 - MinAmp2;
MedVolt = MedVolt + DeVolt;
MedAmp1 = MedAmp1 + DeAmp1;
MedAmp2 = MedAmp2 + DeAmp2;
AMax1 = AMax1 + MaxVerso1;
AMax2 = AMax2 + MaxVerso2;
MaxVolt = 0;
MinAmp1 = 1023;
MaxAmp1 = 0;
MinAmp2 = 1023;
MaxAmp2 = 0;
if(cyccnt == 48){
MedVolt = MedVolt + 2*DeVolt;
MedAmp1 = MedAmp1 + 2*DeAmp1;
MedAmp2 = MedAmp2 + 2*DeAmp2;
Volt = 0.004711*double(MedVolt) + 35;
Amp1 = 0.001025*double(MedAmp1) - 0.045;
Amp2 = 0.001025*double(MedAmp2) - 0.045;
WattSec1 = int((Volt*Amp1) + 0.5);
WattSec2 = int((Volt*Amp2) + 0.5);
display.clearDisplay();
display.setCursor(0,0);
display.print("V");
display.print(int(Volt + 0.5));
if(AMax1 < 24) {
display.println (" No P");
}
else{
display.print(" P");
display.println(WattSec1);
}
if(AMax2 < 24) display.print(" -");
else display.print(" +");
display.print("C");
display.println(WattSec2);
MedVolt = 0;
MedAmp1 = 0;
MedAmp2 = 0;
if(WattSec1>WattSec2){ // Produzione > Consumo
digitalWrite(Led_Rosso, HIGH);
digitalWrite(Led_Verde, LOW);
}
else { // Produzione <= Consumo
digitalWrite(Led_Rosso, LOW);
digitalWrite(Led_Verde, HIGH);
}
AMax1 = 0;
AMax2 = 0;
cyccnt = 0;
while(digitalRead(Sync) == LOW){
}
stcur = 1;
}
}
}
else {
if (digitalRead(Sync) == 0){
stcur = 0;
}
}
sensorValue = analogRead(Volt_pin);
if(sensorValue>MaxVolt) {
MaxVolt=sensorValue;
}
sensorValue = analogRead(Amp1_pin);
if(sensorValue MinAmp1=sensorValue;
}
if(sensorValue>MaxAmp1){
MaxAmp1=sensorValue;
MaxVerso1 = stcur;
}
sensorValue = analogRead(Amp2_pin);
if(sensorValue MinAmp2=sensorValue;
}
if(sensorValue>MaxAmp2){
MaxAmp2=sensorValue;
MaxVerso2 = stcur;
}
}