#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into port 4 on the Arduino or ESP32
#define ONE_WIRE_BUS D4
#define TEMPERATURE_PRECISION 10

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature. 
DallasTemperature sensors(&oneWire);

// Tableaux contenant l'adresse de chaque sonde OneWire | arrays to hold device addresses
DeviceAddress Thermometer = { 0x28,  0x9C,  0x7D,  0x6E,  0x4F,  0x20,  0x1,  0x27 };

void setup() {
  Serial.begin(115200);
  
  // Start up the library
  sensors.begin();

  // locate devices on the bus
  Serial.print("Locating devices...");
  Serial.print("Found ");
  Serial.print(sensors.getDeviceCount(), DEC);
  Serial.println(" devices.");

  // report parasite power requirements
  Serial.print("Parasite power is: "); 
  if (sensors.isParasitePowerMode()) Serial.println("ON");
  else Serial.println("OFF");

  // Vérifie sir les capteurs sont connectés | check and report if sensors are conneted 
  if (!sensors.getAddress(Thermometer, 0)) Serial.println("Unable to find address for Device 0"); 

  // set the resolution to 9 bit per device
  sensors.setResolution(Thermometer, TEMPERATURE_PRECISION);
  
  // On vérifie que le capteur st correctement configuré | Check that ensor is correctly configured
  Serial.print("Device Resolution: ");
  Serial.print(sensors.getResolution(Thermometer), DEC); 
  Serial.println();
}

void printTemperature(String label, DeviceAddress deviceAddress){
  float tempC = sensors.getTempC(deviceAddress);
  Serial.print(label);
  if (tempC == -127.00) {
    Serial.print("Error getting temperature");
  } else {
    Serial.print(" Temp C: ");
    Serial.print(tempC);
    Serial.print(" Temp F: ");
    Serial.println(DallasTemperature::toFahrenheit(tempC));
  }  
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.print("Requesting temperatures...");
  sensors.requestTemperatures();
  Serial.println("DONE");

  // print the device information
  printTemperature("Temperature : ", Thermometer);
  
  delay(5000);
}
