One Wire temperature sensor DS18B20 is very popular and easily available because they are quite cheap and provide satisfactory precision of temperature readings. One wire DS18b20 has operating temperature range from -55°C to +125°C with accurate to ±0.5°C. DS18B20  can easily interface with Raspberry Pi.

This sensor has three pins: VCC, GND and DATA. The voltage range is between 3.0 to 5.5 so this can be easily interfaced with raspberry pi. To communicate with the sensor 1-wire protocol is used. As each DS18B20 sensor has a unique serial code. Therefore we can connect number of them on same line. Lets connect one wire temperature sensor to Raspberry pi.

DS18B20 1-Wire Digital Temperature Sensor

DS18B20 1-Wire Digital Temperature Sensor

VCC to Pi 3.3v Pin

Don’t forget to add 4.7k resister between 5v and data pin.
Our Raspberry Pi acts like a master on a bus to get readings from sensors. The 1-wire communication on GPIO4 is already implemented as kernel module in Raspbian, lets make some config changes to get some temperature readings. Issue following two commands from shell.

Add following line to /boot/config.txt

You can edit that file with nano by running sudo nano /boot/config.txt and then scrolling to the bottom and add dtoverlay=w1-gpio

Add follwing line at the end of file and Ctrl+O to save changes then Ctrl+X to close nano editor.

Now reboot the Raspberry pi.

After rebooting RPi ssh to RPi again, type the following two commands you see below.

modprobe w1-gpio registers the new sensor connected to GPIO4 so that now the Raspberry Pi knows that there is a 1-Wire device connected to the GPIO. modprobe w1-therm tells the Raspberry Pi to add the ability to measure temperature on the 1-Wire system.

To allow the w1_gpio and w1_therm modules to load automatically at boot we can edit the the /etc/modules file and include both modules there where they will be started when the Pi boots up. To do this edit the /etc/modules file:

Add in the w1_gpio and w1_therm modules so that the file looks like the following;

To list all attached sensors issue following command:

Here is output from my Raspberry Pi setup:

To get temperature from sensor run command in this format cat /sys/bus/w1/devices/<ID>/w1_slave i.e

This should read temperature in following format:

In the first line we can see if the reading was successful (“YES”) and in the second line after “t=” is the temperature reading in mile degrees Celsius (21750).

If you want to save data to MySQL/MaridaDB database you can follow next step of this One Wire Temperature Sensor – DS18B20 to MySQL/MariaDB Database