#include <SPI.h>
#include "../MCP3428/MCP3428.h"


// Variables pour stocker les valeurs de calibration
float cal_ph4_voltage = 0;
float cal_ph7_voltage = 0;
float cal_ph10_voltage = 0;
float slope = 0;
float intercept = 0;
float temperature = 25.0; // Température par défaut en °C

void setup() {
	Serial.begin(9600);
	Serial.println("Calibration du pH-mètre...");
	calibrate();
}

void loop() {
	Serial.println("Entrez la température de la solution en °C : ");
	while (Serial.available() == 0) {}
	temperature = Serial.parseFloat();
	Serial.print("Température : ");
	Serial.println(temperature);

	float ph = readPH();
	Serial.print("pH de la solution: ");
	Serial.println(ph);
	delay(1000);
}

void calibrate() {
	Serial.println("Plonger la sonde dans la solution de pH 4.01 et appuyer sur Enter");
	while (Serial.read() != '\n') {}
	cal_ph4_voltage = readVoltage(0);
	Serial.print("Voltage à pH 4.01: ");
	Serial.println(cal_ph4_voltage);

	Serial.println("Plonger la sonde dans la solution de pH 7.00 et appuyer sur Enter");
	while (Serial.read() != '\n') {}
	cal_ph7_voltage = readVoltage(0);
	Serial.print("Voltage à pH 7.00: ");
	Serial.println(cal_ph7_voltage);

	Serial.println("Plonger la sonde dans la solution de pH 10.01 et appuyer sur Enter");
	while (Serial.read() != '\n') {}
	cal_ph10_voltage = readVoltage(0);
	Serial.print("Voltage à pH 10.01: ");
	Serial.println(cal_ph10_voltage);

	// Calcul de la pente et de l'ordonnée à l'origine de la courbe de calibration
	slope = (10.01 - 4.01) / (cal_ph10_voltage - cal_ph4_voltage);
	intercept = 7.0 - slope * cal_ph7_voltage;

	Serial.print("Pente: ");
	Serial.println(slope);
	Serial.print("Ordonnée à l'origine: ");
	Serial.println(intercept);
}

float readPH() {
	float voltage = readVoltage(0);
	float temp_slope = -59.16 * (temperature + 273.15) / 298.15; // Ajustement de la pente de Nernst avec la température
	return (voltage - cal_ph7_voltage) * temp_slope / -59.16 + 7.0;
}

float readVoltage(byte channel) {
	unsigned int command = 0xD0 | (channel << 4); // Configuration de l'ADC
	digitalWrite(CS_PIN, LOW);
	SPI.transfer(command);
	unsigned int high_byte = SPI.transfer(0x00);
	unsigned int low_byte = SPI.transfer(0x00);
	digitalWrite(CS_PIN, HIGH);
	unsigned int value = (high_byte << 8) | low_byte;
	float voltage = (value * 5.0) / 65535.0; // Conversion en tension
	return voltage;
}
