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

// Data wire is connected to pin 2 on the Arduino
#define ONE_WIRE_BUS 2

// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

// Pass the oneWire reference to DallasTemperature library
DallasTemperature sensors(&oneWire);

void setup() {
  // Start serial communication for debugging purposes
  Serial.begin(9600);

  // Initialize the DS18B20 sensor
  sensors.begin();
}

void loop() {
  // Request temperature readings
  sensors.requestTemperatures();
delay(100);
  // Read temperature in Celsius
  float temperatureC = sensors.getTempCByIndex(0);

  // Check if the temperature is valid
  if (temperatureC != -127.00) {
    Serial.print("Temperature: ");
    Serial.print(temperatureC);
    Serial.println(" °C");
  } else {
    Serial.println("Error: Unable to read temperature data");
  }

  delay(1000); // Adjust delay as needed
}

Loading
ds18b20