DS18B20 and STM32
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 we will see how 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 for communication with the micro controller. Let’s see how to program a DS18B20 temperature sensor using STM32.
NOTE:- This code works with STM32CUBEIDE and it uses TIMER to create delay in microsecond. If you don’t know how to do that, go to https://controllerstech.com/create-1-microsecond-delay-stm32/ .
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.
- 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 line low, the master must release the line 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 line low, the master must continue to hold the line 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 are the STEPS, we need to follow to read the temperature from DS18B20