//Three sensors, one bus, LCD by TIM
#include <OneWire.h>
#include <DallasTemperature.h>
// Connect DS18B29 to Arduino pin D12.
const byte ONE_WIRE_BUS = 13;
int8_t led_pin_red = 11;
int8_t led_pin_yellow = 12;
int8_t led_pin_green = 10;
int8_t TEMPERATURE_PRECISION = 12;
// Setup a OneWire instance to communicate with any OneWire devices.
OneWire oneWire(ONE_WIRE_BUS);

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

 byte numDevices = 0;

// Initialization of sensor and serial communication.
void setup()
{
  Serial.begin(115200);

  pinMode(led_pin_yellow, OUTPUT);
  pinMode(led_pin_red, OUTPUT);
  pinMode(led_pin_green, OUTPUT);

  sensors.begin();

  byte address[8];

  while (oneWire.search(address))
  {
    Serial.print("Bus index=");
    Serial.print(numDevices);
    Serial.print(";  Device address=");
    for(byte i = 0; i < 8; i++)
    {
      Serial.print(address[i], HEX);
      Serial.print(" ");
    }
    Serial.println();
    numDevices++;
  }
}

void loop() {
  if (numDevices > 0) {
    sensors.requestTemperatures();

    for (byte i = 0; i < numDevices; i++) {
      digitalWrite(led_pin_yellow, HIGH);
      float temperatureCelsius = sensors.getTempCByIndex(i);

      // Check if the temperature reading is valid
      if (temperatureCelsius != DEVICE_DISCONNECTED_C) {
        int tInt = int(temperatureCelsius);

        digitalWrite(led_pin_green, HIGH);

        Serial.print("Bus index=");
        Serial.print(i);
        Serial.print(";  Temperature=");
        Serial.print(temperatureCelsius);
        Serial.println("°C");

        // Reset the error flag
        sensors.setResolution(i, TEMPERATURE_PRECISION);
      } else {
        // Print an error message if the reading is invalid
        Serial.print("Error reading temperature from sensor at index ");
        Serial.println(i);
        
        digitalWrite(led_pin_red, HIGH);
        // You can choose to handle the error condition here
      }

      digitalWrite(led_pin_yellow, LOW);

      char floatBuffer[20];
      delay(500);
    }
  }
  digitalWrite(led_pin_green, LOW);

  delay(1000);
}