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
| Raspberry Pi Pinout Diagram |

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
- DS18B20 senses temperature
- Converts temperature into digital data
- Sends data through 1-Wire communication
- Raspberry Pi reads data via GPIO4
- Pull-up resistor stabilizes communication
- 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
- Import required libraries
- Enable 1-Wire interface using system commands
- Locate sensor device folder
- Read raw data file from sensor
- Check data validity
- Extract temperature value
- Convert to Celsius
- Display temperature
- 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.