// Marek Sedláček calibration gas sensors TGS26XX
// VUT Fakulta elektrotechniky a komunikašných technológií
// 2021/2022
// po hodine kalibracie: 
// TGS2611 ustálena hodnota = 2.65
// TGS2602 ustálená hodnota = 53.0 (cca)
// TGS2620 ustalena hodnota = 1.53
// su tam drobne zmeny, plus minus 0.09 u TGS2602 dna 26.5.2022

int sensorvalue1 = A0; //TGS2611 
int sensorvalue2 = A1; // TGS2602
int sensorvalue3 = A2; // TGS2620
int val1 =0;
int val2 =0;
int val3 =0;
float voltage1 ;
float voltage2 ;
float voltage3 ;
float RS_1;
float RS_2;
float RS_3;
float ratio_1;
float ratio_2;
float ratio_3;

//---------------------------------------------------

// Metan TGS2611 senzor 1
const float METHAN_LOG10_M_1 = -0.455;
const float METHAN_LOG10_B_1 = 1.683;
const float MAX_PPM_1 = 754;
const float TGS2611_1_R0 = 2.65f;

// Amoniak TGS2602 senzor 2
const float AMONIAK_LOG10_M_2 = -0.3056;
const float AMONIAK_LOG10_B_2 = 0.00458;
const float MAX_PPM_2 = 52;
const float TGS2602_2_R0 = 53.f;

// CO TGS2620 senzor 3
const float CO_LOG10_M_3 = -0.549;
const float CO_LOG10_B_3 = 1.698;
const float MAX_PPM_3 = 131;
const float TGS2620_3_R0 = 1.53f;



void setup() {
  
pinMode(sensorvalue1, INPUT);
pinMode(sensorvalue2, INPUT);
pinMode(sensorvalue3, INPUT);
//pinMode(battery_value, INPUT);
Serial.begin(9600);
}

void loop() {
  
val1 = analogRead(sensorvalue1);
val2 = analogRead(sensorvalue2);
val3 = analogRead(sensorvalue3);

// vypocet napatia 
voltage1 = val1 * 5.0 / 1023.0;
voltage2 = val2 * 5.0 / 1023.0;
voltage3 = val3 * 5.0 / 1023.0;

// vypocet napatia na senzoroch
RS_1 = (5 - voltage1) / voltage1;
RS_2 = (5 - voltage2) / voltage2;
RS_3 = (5 - voltage3) / voltage3;


//prepocet na R0
 float R0_1 = RS_1 / 8.8 ;   // Fresh air TGS2611 - 8.8
 float R0_2 = RS_2 / 1.0 ;   // Fresh air TGS2602 - 1.0
 float R0_3 = RS_3 / 11.1 ;   // Fresh air TGS2620 - 11.1

 // vypočet RS
ratio_1 = RS_1 / 2.65;
ratio_2 = RS_2 / 53;
ratio_3 = RS_3 / 1.53;

float ppm_1 = pow(10, (log10(ratio_1) - METHAN_LOG10_B_1) / METHAN_LOG10_M_1);
float ppm_2 = pow(10, (log10(ratio_2) - AMONIAK_LOG10_B_2) / AMONIAK_LOG10_M_2);
float ppm_3 = pow(10, (log10(ratio_3) - CO_LOG10_B_3) / CO_LOG10_M_3);

 
// R0
  Serial.print("R0 [0]: ");
  Serial.print(R0_1);
  Serial.print("\tR0 [1]: ");
  Serial.print(R0_2);
  Serial.print("\tR0 [2]: ");
  Serial.println(R0_3);

//ratio
  Serial.print("RS/R0 [0]: ");
  Serial.print(ratio_1);
  Serial.print("\tRS/R0 [1]: ");
  Serial.print(ratio_2);
  Serial.print("\tRS/R0 [2]: ");
  Serial.println(ratio_3);

// gas concentration in ppm
  Serial.print("ppm1 [0]: ");
  Serial.print(ppm_1);
  Serial.print("\tppm2 [1]: ");
  Serial.print(ppm_2);
  Serial.print("\tppm3 [2]: ");
  Serial.println(ppm_3);

  Serial.println("- - - - - - - - - - - - - - - - - - - - - - - -");
 
delay(5000);
}
