Measuring a Temperature with DS18B20


DS18B20 is a digital temperature sensor which measures temperatures from -55°C to +125°C. It uses 1-Wire communication protocol. We have only one data pin for sending and receiving data. For more information see DS18B20 datasheet. In this post I will use Raspberry PI-III as a micro controller. For data pin I chose GPIO26. Before using this pin as a 1-Wire, we need to enable 1-Wire communication. You can do it raspi-config or adding the lines below end of the /boot/config.txt file and reboot your Raspberry.



After reboot the system. We should check whether or not device is connected properly. You can see below configuration looks good. 28-0000010edf01 is the my device.

Each DS18B20 contains a unique ROM code that is 64-bits long. The first 8 bits are a 1-Wire family code (DS18B20 code is 28h). The next 48 bits are a unique serial number. The last 8 bits are a CRC of the first 56 bits.

pi@raspberrypi:~ $ ls -l /sys/bus/w1/devices/28-0000010edf01
lrwxrwxrwx 1 root root 0 Dec 25 08:02 /sys/bus/w1/devices/28-0000010edf01 -> ../../../devices/w1_bus_master1/
cat /sys/bus/w1/devices/28-0000010edf01/driver/28-0000010edf01/w1_slave

5c 01 4b 46 7f ff 04 10 a1 : crc=a1 YES
5c 01 4b 46 7f ff 04 10 a1 t=21750

As you see output above t is the temperature. Bu we need to some calculations conver to Celcius.

echo $(cat /sys/bus/w1/devices/28-0000010edf01/w1_slave | tail -n +2 | cut -f 2 -d '=') | awk '{x=$1}END{print(x/1000)}'
while true
                echo $(cat /sys/bus/w1/devices/28-0000010edf01/w1_slave | tail -n +2 | cut -f 2 -d '=') | awk '{x=$1}END{print(x/1000)}'
                sleep 2

  Final Result