#include <OneWire.h>
#include <DallasTemperature.h>
#include <EEPROM.h>
// Pin to which the DS18B20 is connected
#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
DallasTemperature sensors(&oneWire);
// Maximum number of DS18B20 sensors
#define MAX_SENSORS 25
// Function to save the device address to EEPROM
void saveAddressToEEPROM(DeviceAddress deviceAddress, int index) {
int startAddress = index * 8; // Each address is 8 bytes
for (uint8_t i = 0; i < 8; i++) {
EEPROM.write(startAddress + i, deviceAddress[i]);
}
}
// Function to read the device address from EEPROM
void readAddressFromEEPROM(DeviceAddress deviceAddress, int index) {
int startAddress = index * 8; // Each address is 8 bytes
for (uint8_t i = 0; i < 8; i++) {
deviceAddress[i] = EEPROM.read(startAddress + i);
}
}
void setup() {
// Start serial communication
Serial.begin(9600);
// Start the DS18B20 sensor
sensors.begin();
// Search for devices on the bus
oneWire.reset_search();
DeviceAddress deviceAddress;
int sensorCount = 0;
// Search for all devices and save their addresses
while (oneWire.search(deviceAddress)) {
if (sensorCount < MAX_SENSORS) {
Serial.print("Found device with address: ");
for (uint8_t i = 0; i < 8; i++) {
Serial.print(deviceAddress[i], HEX);
if (i < 7) Serial.print(", ");
}
Serial.println();
// Save the address to EEPROM
saveAddressToEEPROM(deviceAddress, sensorCount);
Serial.println("Address saved to EEPROM");
sensorCount++;
} else {
Serial.println("Maximum sensor limit reached.");
break;
}
}
if (sensorCount == 0) {
Serial.println("No DS18B20 temperature sensors are installed.");
}
// To verify, read the addresses back from EEPROM
for (int i = 0; i < sensorCount; i++) {
DeviceAddress readAddress;
readAddressFromEEPROM(readAddress, i);
Serial.print("Read address from EEPROM (sensor ");
Serial.print(i);
Serial.print("): ");
for (uint8_t j = 0; j < 8; j++) {
Serial.print(readAddress[j], HEX);
if (j < 7) Serial.print(", ");
}
Serial.println();
}
}
void loop() {
// Put your main code here, to run repeatedly
}