#include <OneWire.h>
// Define the pin where the DS18B20 data line is connected
#define ONE_WIRE_BUS 4 // GPIO 4 on Raspberry Pi Pico
// Create a OneWire instance
OneWire oneWire(ONE_WIRE_BUS);
void setup() {
// Start serial communication
Serial1.begin(115200);
Serial1.println("DS18B20 Temperature Sensor Initialization");
}
void loop() {
byte data[9];
byte addr[8];
// Search for a device on the OneWire bus
if (!oneWire.search(addr)) {
Serial1.println("No DS18B20 sensor detected!");
oneWire.reset_search();
delay(1000); // Wait for a moment before retrying
return;
}
// Check if the found device is a DS18B20
if (OneWire::crc8(addr, 7) != addr[7]) {
Serial1.println("CRC is not valid!");
return;
}
if (addr[0] != 0x28) {
Serial1.println("Device is not a DS18B20!");
return;
}
Serial1.print("Found DS18B20 with address: ");
for (int i = 0; i < 8; i++) {
Serial1.print(addr[i], HEX);
if (i < 7) Serial1.print(":");
}
Serial1.println();
// Start a temperature conversion
oneWire.reset();
oneWire.select(addr);
oneWire.write(0x44); // Start temperature conversion
delay(750); // Wait for the conversion to complete
// Read the temperature data
oneWire.reset();
oneWire.select(addr);
oneWire.write(0xBE); // Read Scratchpad
// Read 9 bytes from the sensor
for (int i = 0; i < 9; i++) {
data[i] = oneWire.read();
}
// Convert the raw temperature data to Celsius
int16_t rawTemp = (data[1] << 8) | data[0];
float celsius = rawTemp / 16.0;
Serial1.print("Temperature: ");
Serial1.print(celsius);
Serial1.println(" °C");
// Delay before the next reading
delay(1000);
}