#include <OneWire.h>
void setup() {
Serial.begin(115200);
setResolution(4);
dallas(4, 1);
}
void loop() {
unsigned long time = micros();
float celsius = dallas(4, 0);
time = micros() - time;
Serial.print(celsius, 5);
Serial.print(" ");
Serial.print(time);
Serial.println();
delay(1000);
}
float dallas(int x, byte start)
{
OneWire ds(x);
byte data[9];
float celsius;
do {
ds.reset();
ds.write(0xCC); // 0xCC = Skip ROM — address all devices on the bus
ds.write(0xBE); // 0xBE = Read Scratchpad command, to read data from the sensor's memory.
for (byte i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
}
int16_t raw = (data[1] << 8) | data[0];
raw = raw << 3;
if (data[7] == 0x10) {
// "count remain" gives full 12 bit resolution
raw = (raw & 0xFFF0) + 12 - data[6];
}
ds.reset();
ds.write(0xCC); // 0xCC = Skip ROM — address all devices on the bus
ds.write(0x44, 1); // 0x44 = Start temperature conversion, 0 = no parasite power, 1 = with parasite power
if (start) delay(1000);
celsius = (float)raw / 16.0;
} while (start--);
return celsius;
}
void setResolution(int x) {
OneWire ds(x);
// Resolution value (choose one of these):
// 9-bit: 0x1F ~93.75 ms
// 10-bit: 0x3F ~187.5 ms
// 11-bit: 0x5F ~375 ms
// 12-bit: 0x7F ~750 ms
byte addr[8];
ds.reset();
ds.write(0xCC); // 0xCC = Skip ROM — address all devices on the bus
ds.write(0x4E); // 0x4E = Write Scratchpad command
ds.write(0); // TH register (user-defined alarm high threshold, unused here)
ds.write(0); // TL register (user-defined alarm low threshold, unused here)
ds.write(0x3F); // Configuration register — sets resolution to 10-bit
// Optionally: copy scratchpad to EEPROM
ds.reset();
ds.write(0xCC); // 0xCC = Skip ROM — address all devices on the bus
ds.write(0x48); // 0x48 = Copy Scratchpad to EEPROM
}