Temperature sensor

Hi,
this time is turn of temperature sensor.
What we are going to do is to connect read output from 1-Wire Digital Thermometer and show to console.

The sensor we are talking about is Maxim DS18B20+. We need to mount modules driver to read data from sensor and then parse output and show to console.

The sensor has 3 pins, ground (GND), data (DQ) and 3.3V input (VDD):



what we need:
  • Temperature sensor
  • 4.7k ohm resistence
  • a coffe
go to youtube and listen to this: https://www.youtube.com/watch?v=NUgcygzQAwM

ok, let's go.

First of all place sensor on breadboard. Done? ok, then follow these connections:

breadboard negative rail-> GND pin on Raspberry GPIO
breadboard positive rail -> 3.3V pin on Raspberry GPIO
sensor 3.3V pin -> positive rail on breadboard
sensor GND pin -> negative rail on breadboard
on pin of resistor -> data pin on sensor
other pin of resistor -> positive rail on breadboard
data sensor pin (after resistor pin) -> GPIO4 pin on Raspberry

to understand better follow this schema:



and this is the schema in real



before coding enter in your raspberry shell and add this row:   

dtoverlay=w1-gpio

to /boot/config.txt

then if you call those commands:

sudo modprobe w1-gpio
sudo modprobe w1-therm

you are loading sensor drive modules. Now open this folder:
 cd /sys/bus/w1/devices/

in here you'll see a folder with sensor device mounted sutch as  28-000006c7b002

enter in that folder and execute this:
cat w1_slave

 
you'll see two lines of code, in first line we have at the end if the sensor is reading data and on the second line we have the temperature value. All we need is to parser those values...
let's code:




import os
import time

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

temp_sensor = '/sys/bus/w1/devices/28-000006c7b002/w1_slave'

# read row data

def temp_raw():
    f=open(temp_sensor,'r')
    lines=f.readlines()
    f.close()
    return lines

# parse row data
# read row data

def temp_raw():
    f=open(temp_sensor,'r')
    lines=f.readlines()
    f.close()
    return lines

# parse row data
def read_temp():
    lines=temp_raw()
    while lines[0].strip()[-3:] != 'YES':
        time.sleep(0.2)
        lines=temp_raw()

# get temperature output
# we can find it at this row 74 01 4b 46 7f ff 0c 10 55 t=23250
# t=23250

    temp_output = lines[1].find('t=')

    if temp_output != -1:
        temp_string = lines[1].strip()[temp_output+2:]
        temp_c = float(temp_string)/1000.0    # Celsius
        temp_f = temp_c * 9.0 / 5.0 + 32.0    # Fahrenheit
        return 'Celsius: ' + str(temp_c) + '°C', 'Fahrenheit: ' + str(temp_f) + '°F'

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



    

and this is what we have obtained:


to do this i followed this guide that explain better what is done: http://www.modmypi.com/blog/ds18b20-one-wire-digital-temperature-sensor-and-the-raspberry-pi

stay tuned for other projects!

Commenti