DS18B20 Temperature Sensor Raspberry Pi

 1. Introduction

The DS18B20 is a digital temperature sensor that communicates using the 1-Wire protocol. It provides accurate temperature readings and requires only one data pin. It is widely used in IoT and temperature monitoring systems.


2. Components

  • Raspberry Pi
  • DS18B20 Temperature Sensor
  • 4.7kΩ Resistor (Pull-up)
  • Breadboard
  • Jumper Wires

3. Circuit and connections

Raspbery Pi Pinout Circuit
Raspberry Pi Pinout Diagram

Pinout Connection Diagram DS18B20
Pinout Connection DS18B20 Temperature Sensor
Connections:

  • VCC → 3.3V (Pin 1)
  • GND → GND (Pin 6)
  • DATA → GPIO4 (Pin 7)
  • 4.7kΩ resistor between VCC and DATA

4. Detailed Step By Step Circuit working

  1. DS18B20 senses temperature
  2. Converts temperature into digital data
  3. Sends data through 1-Wire communication
  4. Raspberry Pi reads data via GPIO4
  5. Pull-up resistor stabilizes communication
  6. Temperature value is processed and displayed

5. Libraries to be included

import os
import glob
import time

6. Code

import os
import glob
import time

os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')

base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'

def read_temp():
f = open(device_file, 'r')
lines = f.readlines()
f.close()

while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
f = open(device_file, 'r')
lines = f.readlines()
f.close()

equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
return temp_c

while True:
temp = read_temp()
print("Temperature:", temp, "C")
time.sleep(1)

7. Detailed Step By Step Code working

  1. Import required libraries
  2. Enable 1-Wire interface using system commands
  3. Locate sensor device folder
  4. Read raw data file from sensor
  5. Check data validity
  6. Extract temperature value
  7. Convert to Celsius
  8. Display temperature
  9. Repeat continuously

8. Tips

  • Enable 1-Wire in Raspberry Pi settings
  • Use 4.7kΩ pull-up resistor (important)
  • Ensure correct wiring
  • Use waterproof version for outdoor use

9. Uses

  • Temperature monitoring systems
  • Smart home automation
  • Weather stations
  • Industrial temperature control

10. Conclusion

The DS18B20 sensor is highly accurate and easy to use with Raspberry Pi. It is ideal for digital temperature measurement in IoT and automation projects.

തുടക്കക്കാർക്കായുള്ള ഇലക്ട്രോണിക്സ് ലളിതമായി പഠിക്കാം.

Empowering students in Kerala with hands-on technical skills.