DS18B20U shows -37 degrees at room +24

Hi I use ESP32 board, and when I connect the DS18B20U sensor it shows the temperature to me -37 at room +24 and when I heat it the temperature Increases.

#include <OneWire.h>

/* 
 * Получаем температуру от датчиков серии DS18x20 
 */


// Поддерживаемые датчики
#define DS18S20_ID 0x10
#define DS18B20_ID 0x28


// Линия 1-Wire будет на pin 2
OneWire  ds(23);

void setup(void)  {
  Serial.begin(9600);
}


void loop(void) {
  byte i;
  byte present = 0;
  byte data[12];
  byte addr[8];
  
  if (!ds.search(addr)) {
      ds.reset_search();
      return;
  }
  
  if (OneWire::crc8( addr, 7) != addr[7]) {
      Serial.print("CRC is not valid!\n");
      return;
  }
  
  if (addr[0] != DS18S20_ID && addr[0] != DS18B20_ID) {
      Serial.print("Device is not a DS18x20 family device.\n");
      return;
  }
  
  ds.reset();
  ds.select(addr);
  
  // Запускаем конвертацию
  ds.write(0x44, 1);
  
  // Подождем...
  delay(1000);
  
  present = ds.reset();
  ds.select(addr); 

  // Считываем ОЗУ датчика  
  ds.write(0xBE); 

   // Обрабатываем 9 байт
  for ( i = 0; i < 9; i++) {
    data[i] = ds.read();
  }
  
  // Высчитываем температуру :)
  int HighByte, LowByte, TReading, Tc_100, SignBit, Whole, Fract;
  LowByte = data[0];
  HighByte = data[1];

   TReading = (HighByte << 8) + LowByte;
   
   // Проверяем дубак там или нет
   SignBit = TReading & 0x8000; 
   
   // Если на улице дубак :)
   if (SignBit) { 
       TReading = (TReading ^ 0xffff) + 1; 
   }
   
   // Умножаем на (100 * 0.0625) или 6.25
   Tc_100 = (6 * TReading) + TReading / 4;

   // Отделяем целые от дробных чисел
   Whole = Tc_100 / 100;
   Fract = Tc_100 % 100;

   Serial.print("Temperature: ");

   // Если на улице дубак напишем минус перед цифрами :)
   if (SignBit) { 
      Serial.print("-");
   }
   
   Serial.print(Whole);
   Serial.print(".");
   
   if (Fract < 10) {
      Serial.print("0");
   }
   
   Serial.print(Fract);
   Serial.print("\n");
}

Hi @antons15

Would the sensor be inside the box with the ucontroller or some other electronics?

Post an image of where the DS18B20 is located

RV mineirin

And I try with this code and all the same:

#include <OneWire.h>                  // Библиотека протокола 1-Wire
#include <DallasTemperature.h>        // Библиотека для работы с датчиками DS*

#define ONE_WIRE_BUS 23              // Шина данных на 10 пине

OneWire oneWire(ONE_WIRE_BUS);        // Создаем экземпляр объекта протокола 1-WIRE - OneWire
DallasTemperature sensors(&oneWire);  // На базе ссылки OneWire создаем экземпляр объекта, работающего с датчиками DS*

void setup(void)
{
  Serial.begin(9600);                 // Настраиваем Serial для отображения получаемой информации
  sensors.begin();                    // Запускаем поиск всех датчиков
}

void loop(void)
{ 
  Serial.println("Requesting temperatures...");
  sensors.requestTemperatures();      // Запускаем измерение температуры на всех датчиках
  
  // Когда температура измерена её можно вывести
  // Поскольку датчик всего один, то запрашиваем данные с устройства с индексом 0
  Serial.print("Temperature for the device 1 (index 0) is: ");
  Serial.println(sensors.getTempCByIndex(0));  
}![2021-08-31_17-34-56|511x500](upload://1pOKSH0NnWcWTanjnKOeAZyYq0N.jpeg)

```![2021-08-31_17-34-56|511x500](upload://1pOKSH0NnWcWTanjnKOeAZyYq0N.jpeg)

no boxes, just soldered to the wires

Post an image of where the DS18B20 is located

RV mineirin

Be careful what you wish for :smiley:

I would print out (serial monitor) the "raw" sensor data. Then compare it to Table 1 in the DS18B20 specification.

@antons15
Thry the following sketch which does functional check on a DS18B20 temperature sensor.

//12-bit default resolution; external power supply
#include<OneWire.h>
OneWire ds(23);  //IO Pin-23 with which the data line of the senosr is connected.
byte addr[8];         //to hold 64-bit ROM Codes of DS1
byte data[9];        //buffer to hold data coming from DS18B20

void setup() 
{
  Serial.begin(9600);
  ds.reset();
  ds.search(addr);  //collect 64-bit ROM code from sensor 
}

void loop()
{
 //----------------------------
 ds.reset();       //bring 1-Wire into idle state
 ds.select(addr); //slect with DS18B20 sensor with address in addr[] array
 ds.write(0x44);    //conversion command
 delay(1000);   //insert max conversion time or poll status word
 //---------------------------
 ds.reset();
 ds.select(addr);  //selectimg the desired DS18B20
 ds.write(0xBE);    //Function command to read Scratchpad Memory (9-byte)
 ds.read_bytes(data, 9); //data comes from DS and are saved into buffer data[]
 //---------------------------------
  int16_t raw = (data[1] << 8) | data[0]; //---data[0] and data[1] contains temperature data : 12-bit resolution-----
  float myTemp = (float)raw / 16.0;  //12-bit resolution
  Serial.println(myTemp, 2);  //show two-digit after decimal point
}

Hi @antons15 I have test your sketch :

Results :

Requesting temperatures...
Temperature for the device 1 (index 0) is: 28.00
Requesting temperatures...
Temperature for the device 1 (index 0) is: 28.00
Requesting temperatures...
Temperature for the device 1 (index 0) is: 28.00
Requesting temperatures...
Temperature for the device 1 (index 0) is: 28.00
Requesting temperatures...
Temperature for the device 1 (index 0) is: 28.06
Requesting temperatures...
Temperature for the device 1 (index 0) is: 28.00
Requesting temperatures...
Temperature for the device 1 (index 0) is: 28.06

....

The temperature here is 28.xx now.
I have use MEGA.

I think your sensor is measuring your hand temperature.

RV mineirin

DS
for me it dose't work :frowning:

That's the sign of a total lack of communication between the Arduino and the sensor. So first check your connections and pullup, scope the signal pin to see if there's communication going on etc.

I have also tested @antons15's skecth of Post-1 in my MEGA. The sketch works fine.

emperature: 30.00
Temperature: 30.00
Temperature: 30.00
Temperature: 30.00
Temperature: 30.50
Temperature: 30.50
Temperature: 31.00
Temperature: 31.00
Temperature: 31.00
Temperature: 31.00
Temperature: 31.00

That's a good thing to have confirmed.
Like I said, his problem is likely on the hardware side or a very fundamental software issue. The DS18B20 library always reports -127 if the data readout fails altogether and only 0's are read by the host.

1 Like

The sketch of my Post-9 works well in my MEGA.

29.50
29.50
29.50
30.00
29.50
29.50
29.50
29.50
30.00

Now, you have two working sketches. Change the sensor and try again. Please do not forget to connect 4.7k pull-up with data-pin of the sensor.

Probably, loose connection in the breadboard. The DS18B20 is very sensitive to bad contacts.

In this case, I would directly solder the sensor legs with one end of the jumper wires..

Yeah, that might be the problem. It could also be a short between adjacent pins that shouldn't be shorted. He's using an smd SOP-8 (if memory serves and my eyes don't lie to me) which is kind of challenging to suspend in the air like this with pins soldered to it....I wouldn't be surprised if there's a short there somewhere.

@antons15 when working with SMD components in a temporary setup, maybe this bag of tricks serves you well: Techniques and Strategies for Building Electronic Circuits - YouTube
Haven't tried it because I generally just lay out and etch a PCB, but this seems much quicker for some rapid prototyping.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.