About the DS18B20
![]() |
Dallas DS18B20 |
The Rasbian distribution has built in support for the 1 wire protocol making it easy to get up and running.
Connecting the temperature sensor
The sensors has three legs:- Ground
- Data
- Either 3.3v or 5v
Use the following diagram to wire everything up. Connect pin 1 to GND, connect pins 2 & 3 with a 4.7kΩ resistor, connect pin 3 to 3.3V and then connect pin 2 to the Raspberry PI's GPIO pin 4.
![]() |
Wiring the DS18B20 |
sudo modprobe w1-gpio
sudo modprobe w1-therm
It will look like nothing happened but you will now be able to see the sensor, type
ls /sys/bus/w1/devices
28-000004e53685 w1_bus_master1
This is the output I get when I run this on my machine, the sensors is indicated by the file starting with "28", the numbers that come after that are different for each device (they have unique addresses) so yours will differ. To read the data type the following (substituting your device number)
cat /sys/bus/w1/devices/28-xxxxxxxxxxxx/w1_slave
a6 01 4b 46 7f ff 0a 10 f6 : crc=f6 YES a6 01 4b 46 7f ff 0a 10 f6 t=26375
If the first line ends with "YES" then the temperature is available and it the value at the end of the second line. In this example the temperature is 2637 / 1000 = 26.375°C.
Here is some sample Python code
#!/usr/bin/python
import os
from datetime import datetime
device_address = "28-000004e53685" # Change this to your specific value
device_file_name = "/sys/bus/w1/devices/"+ device_address +"/w1_slave"
def read_temperature(device_file):
# Make sure we have the correct kernel modules loaded
os.system("/sbin/modprobe w1_gpio")
os.system("/sbin/modprobe w1_therm")
temp_file = open(device_file)
text = temp_file.read().split("\n")
temp_file.close()
if (len(text) > 0 and text[0].endswith("YES")): # We have some output
# We have data so grab the last chars of the second line (i.e. the temperature)
position = text[1].find("t=")
if (position != -1):
print position+2
return int(text[1][-(len(text[1]) - position - 2):])
else:
return -100000
else:
retun -100000
raw_temp = read_temperature(device_file_name)
print " Raw temp: ", raw_temp
print "Temperature: ", round(raw_temp / 1000.0, 1)
Save the code to a file called something like read-temp.py make it executable with chmod +x read-temp.py and the run it with
./read-temp.py and it will display the current temperature.Raw temp: 26562 Temperature: 26.6
Try putting your thumb on top of the sensor and re-running the code and you'll see the value read has gone up.
In my next blog I who how to add the LCD display to show the current temperature and how to log the data over time and produce a graph with gnuplot showing how the temperature has fluctuated.
No comments:
Post a comment