#if 0
//Regulácia ohrevu valca extrúzneho stroja
#include <Arduino.h>
#include <driver/gpio.h>
#include <Thermocouple.h>
#include <MAX6675_Thermocouple.h>

template<class T> inline Print &operator <<(Print &obj, T arg) {obj.print(arg); return obj;} //Serial <<

//SPI
#define SCK_PIN 22
#define CS_PIN 2
#define SO_PIN 19

#define ZERO_CROSS_DETECTION_PIN GPIO_NUM_16
#define SSR GPIO_NUM_17

bool zero_cross_detection = false; //detekcia nuly

//okno
unsigned long window_start_time = 0;
int window_size = 2000; // 2 [s]

//PID konstanty
//Ladenie bude prebiehat na realnych zariadeniach
float kp = 1;
float ki= 0;
float kd = 0;
float PID_p = 0;
float PID_i = 0;
float PID_d = 0;

//PID premenne
int x = 0; //akcna_velicina
float e = 0; //regulacna_odchylka
float e_prev = 0; //predchadzajuca regulacna odchylka
float currentTime, prevTime, elapsedTime; //aktualny, predchadzajuci a uplynuly cas

//dalsie premenne
float omega = 0; //riadiaca velicina
float y = 0; //regulovana velicina

Thermocouple* thermocouple = NULL;

void setup()
{
    Serial.begin(115200);
    thermocouple = new MAX6675_Thermocouple(SCK_PIN, CS_PIN, SO_PIN); //snimac teploty
}

void loop()
{
    //nastavenie riadiacej veliciny
    if(Serial.available()>0) 
    {
        omega = Serial.parseInt();
    }
    //nacitanie aktualnej regulovanej veliciny 
    y = thermocouple->readCelsius();
    //vypis
    Serial << "Nastavena teplota = " << omega << "\n";
    Serial << "Aktualna teplota = " << y << "\n\n";
    
    e = omega - y; //Vypocet regulacnej odchylky

    PID_p = kp * e; //Vypocet P zlozky
    PID_i = PID_i + (ki * e); //vypocet I zlozky
    //if(PID_i > Max) PID_i = Max;
    //else if(PID_i < Min) PID_i = Min;
    prevTime = currentTime; //zapametanie si predchadzajuceho casu
    currentTime = millis(); //nacitanie aktualneho casu
    elapsedTime = (currentTime - prevTime); //vypocet uplynuleho casu
    PID_d = kd*((e - e_prev)/elapsedTime); //vypocet D zlozky
    x = PID_p + PID_i + PID_d; //vypocet akcnej veliciny
    e_prev = e; //zapametanie si aktualnej chyby
    
    //zamedzenie akcnej velicine presiahnut velkost okna
    if(x > window_size) x = window_size;
    if(x < 0) x = 0;

    //Akcny zasah ----------------------------------------------------
    //Spinanie v okne so spinanim v nule------------------------------
    //pocitanie od 0 - window_size
    if((millis() - window_start_time) > window_size) window_start_time += window_size;

    if((x > 200) && (x > (millis() - window_start_time))) // x>100 aby pri malom regulacnom zasahu rele nespinalo 
    {
    while(!zero_cross_detection) 
    {
        int zero_state = digitalRead(ZERO_CROSS_DETECTION_PIN);
        if(digitalRead(ZERO_CROSS_DETECTION_PIN) != zero_state)
        {
            zero_cross_detection = true;
        }
    }
    digitalWrite(SSR,HIGH);
    zero_cross_detection = false;
    }
    else digitalWrite(SSR,LOW);
}
#endif