My Account

Wish List (0)

Saved Carts


GPIO & Python (7/9) - Temperature Sensor

February 22, 2017

In this project you will learn how to wire and program a temperature sensor. Let’s see how hot the room is.

Things you will need:

Raspberry Pi + SD Card
Keyboard + Mouse
Monitor + HDMI Cable
Power Supply
1x Red LED
1x Blue LED
2x 330Ω Resistor
5x M/M Jumper Wire
7x M/F Jumper Wire
1x Button
1x Buzzer
1x DS18B20 Temperature Sensor
1x 4k7Ω Resistor


Latest version of Rasbian installed on your SD Card
Raspberry Pi setup with a keyboard, mouse and monitor

1. First we need to enable I2C on our Raspberry Pi. We do this by opening
the raspi-config menu.

sudo raspi-config

2. We then need to go to the Interfacing Options menu.

3. Select I2C and then Yes to enable it.

4. Next we need to enable the 1-wire I2C library. To do this we need to edit the boot config.txt file

 sudo nano /boot/config.txt

5. Scroll down to the bottom of the file and add the following line:


6. Now reboot

 sudo reboot

7. Change the current directory to our gpio_python_code directory:

cd gpio_python_code

8. Create a file for our temperature script:


9. Edit the script using nano and add the following code:


import glob
from time import sleep

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()
    return lines

def read_temp():
    lines = read_temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        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:

10. Execute your script

sudo python

Last update: February 22, 2017


Leave a Comment

Leave a Reply

* Name:
* Comment:
* E-mail: (Not Published)
Website: (Site url with http://)
Verification code: