RaspberryPI Tutorials

Digital Temperature Sensor with Raspberry Pi (DS18B20)

By on 13 Dicembre 2014

This is a complete example for read a Temperature from your raspberry pi using 2 simple components.

  1. Dallas DS18B20 Digital Termometer Sensor
  2. 4.7 K PullUp Resistor

1. Create the phyton script

With your terminal or from your GUI create a file thermometer.py and edit it with this:

Write this:

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_raw():
    f = open(device_file, 'r')
    lines = f.readlines()
    f.close()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines = read_temp_raw()
    equals_pos = lines[1].find('t=')
    if equals_pos != -1:
        temp_string = lines[1][equals_pos+2:]
        temp_c = float(temp_string) / 1000.0
        temp_f = temp_c * 9.0 / 5.0 + 32.0
        return temp_c, temp_f

while True:
	print(read_temp())	
	time.sleep(1)

 

 

 

2.Build the Circuit

This is the sample connection with your pi.

raspberry-pi-ds18b20-connections

3.Read your temperature

Open the terminal of your pi and execute this commands;

sudo su
python thermometer.py

You should see every second the temperture in °C and °F like this:

(23.875, 74.975)
(23.812, 74.86160000000001)
(23.687, 74.6366)
(23.687, 74.6366)
(24.25, 75.65)
(24.687, 76.4366)
(25.0, 77.0)
(25.187, 77.3366)
(25.375, 77.675)
(25.5, 77.9)
(25.625, 78.125)
(25.75, 78.35)
(25.812, 78.4616)
(25.875, 78.575)
(25.937, 78.6866)
(25.937, 78.6866)
(25.937, 78.6866)
(25.625, 78.125)
(25.375, 77.675)
(25.125, 77.225)
(24.875, 76.775)
(24.687, 76.4366)
(24.5, 76.1)
(24.312, 75.7616)

 

TAGS
RELATED POSTS

LEAVE A COMMENT

IL FALCY
Turin, Italy

Hi my name is Falcy and this is my World! I use this blog theme to tell people my story. Through all the places and things I see around the world, there isn't a best way to share my experience! Follow my daily updates and discover with me the essence of traveling!

Visited Places