float kesalahan;
float integralKesalahan;
float derivatifKesalahan;
float kesalahanLalu = 0;
float Kp, Ki, Kd;
float setPointTemp;
 
//Pin
int sensorPin = A0;
int Pemanas = 2;
 
//konstanta
#define Ksensor 100/1023 //faktor koreksi sensor panas
 
void setup() {
  pinMode(Pemanas, OUTPUT);
  Serial.begin(9600);

   
  setPointTemp = 28;
  Kp = 1;
  Ki = 0.5;
  Kd = -0.2;
}
 
void loop() {
  float sensor = 1.0 * analogRead(sensorPin) * Ksensor;

  float respon = hitungPID(setPointTemp, sensor);


  analogWrite(Pemanas, respon);
  Serial.print("Setpoint ");
  Serial.println(setPointTemp);
  Serial.print("Feedback ");
  Serial.println(sensor);
  Serial.print("PID Out ");
  if(respon > 100.0) {respon = 100.0;}; // Scaling ala-ala :D
  if(respon < 0.1) {respon = 0.0;}; // Scaling ala-ala :D
  Serial.println(respon);

  delay(2000);


}
 
float hitungPID(float setPointTemp, float sensor)
{
  kesalahan = setPointTemp - sensor;
  integralKesalahan += kesalahan;
  derivatifKesalahan = kesalahan - kesalahanLalu;
  kesalahanLalu = kesalahan;
   
  return (Kp * kesalahan) + (Ki * integralKesalahan) + (Kd * derivatifKesalahan);
}