Reading the temperature from a DS18B20 Digital Thermometer ## Pin connections -[http://www.jamesrobertson.me.uk/dynarex/2016/feb/20/raspberry-pi-to-ds18b20-connections.xml] ## Configuring the sensor Append the following entry in the file /boot/config.txt:
dtoverlay=w1-gpio,gpiopin=21Reboot the Raspberry Pi. ## Identifying the device unique ID Use the following commands:
cd /sys/bus/w1/devices lsIn my directory I observed the file device unique ID *28-0000049a0085*. I then typed `cd 28-0000049a0085`, followed by `ls`, followed by `cat w1_slave`. I observed the following file contents:
22 01 4b 46 7f ff 0e 10 4a : crc=4a YES 22 01 4b 46 7f ff 0e 10 4a t=18125## Example #!/usr/bin/env ruby # file: ds18b20.rb def gettemp(id: nil) return 'gettemp error: please supply an id' unless id filename = 'w1_slave' filepath = File.join('/sys/bus/w1/devices/', id, filename) unless File.exists? filepath then return 'gettemp error: file doesn\'t exist -> ' + filepath end buffer = File.read filepath a = buffer.lines crc = a.shift =~ /YES$/ crc ? (a.shift[/t=(\d+)/,1].to_f / 1000).round(3) : 99999 end if __FILE__ == $0 then puts "Temp : %s" % gettemp(id: '28-0000049a0085') end Output:
Temp : 18.125Note: The above code can also be executed from within a Docker container. ## Resources * DS18B20 Digital Temperature Sensor Chip Dallas http://www.jamesrobertson.me.uk/cpages/2016/feb/20/ds18b20-digital-temperature-sensor-chip-dallas-ebay-co-uk.html * Raspberry Pi 1- Wire Digital Thermometer Sensor (DS18B20) http://www.raspberrypi-spy.co.uk/2013/03/raspberry-pi-1-wire-digital-thermometer-sensor/ ds18b20 temperature sensor raspberrypi