I have covered few temperature sensors in the past eg- LM35, DHT11, DHT22 and also the internal temperature sensor of the STM32 itself. Today in this tutorial I am going to interface DS18B20 temperature sensor with STM32.
The DS18B20 digital thermometer provides 9-bit to 12-bit Celsius temperature measurements and has an alarm function with non-volatile user-programmable upper and lower trigger points. Like DHT11 and DHT22, DS18B20 also communicates over a 1-Wire bus that by definition requires only one data line (and ground) for communication with the micro controller. Let’s see how to program a ds18b20 temperature sensor using STM32.
NOTE:- This code now works with STM32CUBEIDE and it uses TIMER to create delay in microsecond. If you don’t know how to do that, watch the video on my channel on YouTube.
I am going to skip the Cube mx setup process as it’s usual one only. I am using pin PA1 as the data pin for the sensor and controller is running at it’s maximum frequency. Also I am NOT going to use DWT library for the delay in microseconds, as it is shown in the Video. I am using TIMER for the delay purpose.
It will be included in the code when you download it below. We need to write few functions for the sensor. They are as follows..
In order for the sensor to work, we need to initialize it every time. According to the datasheet, the initialization is done by pulling the data pin LOW for 480 us and than reading the pin for the presence pulse sent by sensor. Here is the function for that
To write a BIT to the sensor, we need to perform some operation on the data line. To generate a Write 1, after pulling the 1-Wire bus low, the master must release the 1-Wire bus within 15µs. When the bus is released, the 5kΩ pullup resistor will pull the bus high.
To generate a Write 0 time slot, after pulling the 1-Wire bus low, the master must continue to hold the bus low for the duration of the time slot (at least 60µs).
A read time slot is initiated by the master device pulling the 1-Wire bus low for a minimum of 1µs and then releasing the bus. After the master initiates the read time slot, the DS18B20 will begin transmitting a 1 or 0 on bus. It transmits a 1 by leaving the bus high and transmits a 0 by pulling the bus low. When transmitting a 0, the sensor will release the bus by the end of the time slot, and the bus will be pulled back to its high idle state by the pull-up resister.
The following is the sequence for reading temperature from the ds18b20