Multiple DS18B20 sensors using UART
I have covered different one wire sensors in the past, including the DS18B20. If you recall, we used the method where we check if the pin is high for the given period of time, to identify if the bit is a ‘1’ or a ‘0’.
There seems to be another approach towards these one wire sensors, and that is using the UART.
This tutorial will cover how to interface DS18B20 sensor with STM32, but using the UART. Also we will see the working of the multiple DS18B20 sensors.
The CubeMX setup is as shown below
- As shown above, we need to use the Half Duplex Mode.
- Keep every parameter to default state.
- In the NVIC, enable the global interrupt.
NOTE:- It is recommended to use the USART instead of UART. I tried testing it with UART but it doesn’t seems to work.
This is all the setup needed in CubeMX.
After the code is generated, include the library files onewire.c and onewire.h
First of all we need to define the UART instance we are using
This is defined in the onewire.c file (line 23 onwards). Since I am using USART 1, I have defined it.
Next we will define the number of sensors we have connected to the single pin.
The number of devices needed to be defined in 2 different places. In the onewire.c file (line 26) and in onewire.h file (line 26).
I have connected 2 DS18B20 sensors, so I have defined 2.
This completes the setup process, now we will take a look at the code.
- First of all we will declare the external float array, Temp.
- This array is already defined in the onewire.c file, and this is why we need to define it as an external array here.
- This will basically store the temperature values from different sensors we have connected.
- Inside the main function, we will call the get_Romid()
- This function will scan for all the connected sensors, and sort them according to the ascending order of their IDs.
- Finally inside the while loop, we will call the get_Temperature()
- This will read the temperature from the connected sensors, and the values will be stored in the Temp variable.
- It is advised that you provide at least 1 second delay between two readings.
Below is the image of the debugger with 2 sensors connected.
I am holding one of the sensors, and you can see the reading for both is slightly different.
- STM32 Ethernet #10 HTTP Server (Basic) using LWIP NETCONN (RTOS) May 18, 2022
- STM32 Ethernet #9 TCP Server and Client using LWIP NETCONN (RTOS) April 26, 2022
- STM32 Ethernet #8 UDP Client using LWIP NETCONN (RTOS) April 16, 2022
- STM32 Ethernet #7 UDP Server using LWIP NETCONN (RTOS) April 9, 2022
- GPS (Neo 6M) with STM32 March 9, 2022
- BME280 with STM32 January 8, 2022