Reading the temperature from a DS18B20 Digital Thermometer

Pin connections

rpi_pin connects_to
3.3v VCC(leg1)+resistor(10k)+DATA(leg2)
GPIO21 DATA(leg2)
GROUND GND(leg3)

Configuring the sensor

Append the following entry in the file /boot/config.txt:

dtoverlay=w1-gpio,gpiopin=21

Reboot the Raspberry Pi.

Identifying the device unique ID

Use the following commands:

cd /sys/bus/w1/devices
ls

In 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.125

Note: The above code can also be executed from within a Docker container.

Resources