Raspberry - 1wire DS18B20 Temperature Sensor

Raspberry projects

Raspberry - 1wire DS18B20 Temperature Sensor

Messaggio da leggereda root » 09/01/2019, 16:29



DS18B20 Connections:
VCC = +3.3V
signal = GPIO 4 (pin 7)
R = 4.7 Kohm


add the following line to /boot/config.txt:

nano /boot/config.txt

Codice: Seleziona tutto

reboot the device

testing if everything works:
Codice: Seleziona tutto
    sudo modprobe w1-gpio
    sudo modprobe w1-therm
    cd /sys/bus/w1/devices
    cd 28-xxxx (change this to match what serial number pops up)
    cat w1_slave

in our case:
cat /sys/bus/w1/devices/28-041674ca85ff/w1_slave

Codice: Seleziona tutto
root@InetRadio:~# cat /sys/bus/w1/devices/28-041674ca85ff/w1_slave
90 01 4b 46 7f ff 0c 10 33 : crc=33 YES
90 01 4b 46 7f ff 0c 10 33 t=25000

note: the temperature will be at the end of the second line, in 1/000 degrees C. So, in the example above, the temperature is actually read as 25.000 and then 25.000 degrees Celsius.



nano temperature.py

Codice: Seleziona tutto
import os
import glob
import time
import subprocess
import locale
locale.setlocale(locale.LC_ALL, '')

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

def updatetemperature():
    maxTemperature = 26 # max temperature setting
    valore = read_temp
    valore = float(valore())   
         if valore > maxTemperature:
           rc = subprocess.call("/root/emergenza-temperatura.sh"); #print('temperatura eccessiva')  # scrip to be lauched

while True:
   print(read_temp()),'C' # comment out this line if you don't want the temperature printed on cli

nano emergenza-temperatura.sh

Codice: Seleziona tutto
/bin/echo "WARNING! Excessive Temperature > 26 degrees C"
# do something else here


to launch the control in background:

/usr/bin/python /root/temperature.py &

then put your finger on the sensor and test the program, you shoud see on the cli the following message:

Codice: Seleziona tutto
WARNING! Excessive Temperature > 26 degrees C
Avatar utente
Messaggi: 428
Iscritto il: 10/04/2012, 10:55
Località: Turin

Torna a Raspberry

Chi c’è in linea

Visitano il forum: Nessuno e 2 ospiti