One Wire temperature sensor DS18B20 is very popular and easily available because they are quite cheap and provide satisfactory precision of temperature readings. One wire DS18b20 has operating temperature range from -55°C to +125°C with accurate to ±0.5°C. DS18B20 can easily interface with Raspberry Pi.
This sensor has three pins: VCC, GND and DATA. The voltage range is between 3.0 to 5.5 so this can be easily interfaced with raspberry pi. To communicate with the sensor 1-wire protocol is used. As each DS18B20 sensor has a unique serial code. Therefore we can connect number of them on same line. Lets connect one wire temperature sensor to Raspberry pi.
GND to PI GND
DATA to GPIO 04
VCC to Pi 3.3v Pin
Don’t forget to add 4.7k resister between 5v and data pin.
Our Raspberry Pi acts like a master on a bus to get readings from sensors. The 1-wire communication on GPIO4 is already implemented as kernel module in Raspbian, lets make some config changes to get some temperature readings. Issue following two commands from shell.
Add following line to /boot/config.txt
You can edit that file with nano by running sudo nano /boot/config.txt and then scrolling to the bottom and add dtoverlay=w1-gpio
1 |
sudo nano /boot/config.txt |
Add follwing line at the end of file and Ctrl+O to save changes then Ctrl+X to close nano editor.
1 |
dtoverlay=w1-gpio |
Now reboot the Raspberry pi.
1 |
sudo reboot |
After rebooting RPi ssh to RPi again, type the following two commands you see below.
1 2 |
sudo modprobe w1-gpio sudo modprobe w1-therm |
modprobe w1-gpio registers the new sensor connected to GPIO4 so that now the Raspberry Pi knows that there is a 1-Wire device connected to the GPIO. modprobe w1-therm tells the Raspberry Pi to add the ability to measure temperature on the 1-Wire system.
To allow the w1_gpio and w1_therm modules to load automatically at boot we can edit the the /etc/modules file and include both modules there where they will be started when the Pi boots up. To do this edit the /etc/modules file:
1 |
sudo nano /etc/modules |
Add in the w1_gpio and w1_therm modules so that the file looks like the following;
1 2 3 4 |
# /etc/modules: kernel modules to load at boot time. # This file contains the names of kernel modules that should be loaded # at boot time, one per line. Lines beginning with "#" are ignored. # Parameters can be specified after the module name. w1-gpio w1-therm |
To list all attached sensors issue following command:
1 |
cat /sys/bus/w1/devices/w1_bus_master1/w1_master_slaves |
Here is output from my Raspberry Pi setup:
1 2 3 4 5 6 7 |
root@pihome:~# cat /sys/bus/w1/devices/w1_bus_master1/w1_master_slaves 28-000006d86388 28-000006d7c4e8 28-000006d73924 28-000006d71f15 28-03156520b4ff 28-01156572dbff |
To get temperature from sensor run command in this format cat /sys/bus/w1/devices/<ID>/w1_slave i.e
1 |
cat /sys/bus/w1/devices/28-000006d71f15/w1_slave |
This should read temperature in following format:
1 2 3 |
root@pihome:~# cat /sys/bus/w1/devices/28-000006d71f15/w1_slave 5c 01 4b 46 7f ff 04 10 a1 : crc=a1 YES 5c 01 4b 46 7f ff 04 10 a1 t=21750 |
In the first line we can see if the reading was successful (“YES”) and in the second line after “t=” is the temperature reading in mile degrees Celsius (21750).
If you want to save data to MySQL/MaridaDB database you can follow next step of this One Wire Temperature Sensor – DS18B20 to MySQL/MariaDB Database
29 comments
is this project available to download? i can not download any files from download url
thank you
Hi, i have PiHome smart heating control running in production for over year now. i have used lots of open sources bits/code in this project so i m not sure what their license are and can i modify and publish or do i need owners consent? or i can publish and put their name somewhere in the code? i need some one to spend bit of time on this with me so if uou have spare time and want to help me to make this project public please feel free to contact me at [email protected]
thank you for your comments
WJ
Hi jhm,
this project is available to download now. link
This is a great project I would like to try it out.
Just one note, the Raspberry Pi GPIO pins are only rated for voltages between 0V and 3.3V. If you connect the VCC pin on the DS18B20 and the 4.7k resistor to the Pi 5V pin immediate damage will occur and will render the input permanently non-functional as there is no over-voltage protection.
I know this from my own experience 😉
Here’s a useful link for the GPIO specifications:
http://www.mosaic-industries.com/embedded-systems/microcontroller-projects/raspberry-pi/gpio-pin-electrical-specifications#rpi-gpio-input-voltage-and-output-current-limitations
Hi Nah,
i know but i m using 5v for DS18B20 sensors, i had lots of trouble reading reliable temperature reading while using 3.3v. perhaps i have about 10m long cable connected to DS18B20 and voltage get dropped? never had time to check this. but thank you for sharing link.
Admin
do you have any script or any way of saving this info in database? something that read multiple temperature sensors and save reading along with temperature sensors id to database.
Thanx
Hi Garey,
yes i do have one python script for this very purpose, i need to change few bits before i can share it with you.
Admin
Hi!
Will someone help you?
How do I know my DS18B20 sensor that connects to gpio 4. Configure the web interface, putty in the see
28-051692022cff.
Thanks for all the help.
Pepe
Pepe,
sorry dont understand what you are asking here, if you want to know about directly connected sensors with Raspberry Pi, you need to run gpio_ds18b20.py and enable it in cronjob as well.
I’m sorry that my question is incomprehensible.
(Google translator)
Error while running gpio_ds18b20.py.
File “/var/www/cron/gpio_ds18b20.py”, line 12
print bc.hed + ” ”
^
SyntaxError: Missing parentheses in call to ‘print’
what should I do to use the sensor for boiler control?
Thanks
Pepe,
did you download this python file from Github?
https://github.com/pihome-shc/pihome/blob/master/cron/gpio_ds18b20.py
Hi!
Yes, the whole raspberry img.file
and it contains this file.
can you try to download this file and run it
https://github.com/pihome-shc/pihome/blob/master/cron/gpio_ds18b20.py
Hi!
I downloaded and changed the file.
I’ve run Python 2.7.13.
He made this mistake:
Traceback (most recent call last):
File “/var/www/cron/gpio_ds18b20.py”, line 88, in
insertDB (IDs, temperature)
File “/var/www/cron/gpio_ds18b20.py”, line 53, in insertDB
cur.execute (‘SELECT COUNT (*) FROM
nodes
where node_id = (% s)’, (IDs [i]))File “/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py”, line 210, in execute
query = query% args
TypeError: not all argument converted during string formatting
The problem is that I don’t understand that.
Can you help?
I managed to solve it.
I found the solution in a previous post.
It only works with pyton 2.
Another question.
How do I set my own location to show the weather here
Thanks.
Hi Pepe…
First, you need to create an account at openweathermap:
Get an API key, copy that into your pihome.system table together with your city and country. The 5-day forecast is free, I think to make the 6-day forecast work you would need to pay?
@artlab, 6 days works for me and i m using free api key.
That’s odd… I just checked again and I still get ” HTTP/1.1 401 Unauthorized” for the ‘daily’… the current and 3-hour come down just fine. Maybe it has to do with when you signed up? Their docs suggest that the ‘current’ and ‘5day/3hour’ data is free, but the ’16day’ (which uses the ‘ api.openweathermap.org/data/2.5/forecast/daily?q=…’ call) is only available by paid subscription. My full error:
PHP Warning: file_get_contents(http://api.openweathermap.org/data/2.5/forecast/daily?q=***my town***,UK&appid=***my API key***): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized
in /var/www/cron/weather_update.php line...
[The line number refers to ‘$json = file_get_contents($weather_sixdays_api);’]
It doesn’t personally bother me as the 3-hour data is enough for my purposes – anything over 5 days is unreliable. I have found the openweathermap API to be a bit flaky to be honest… more than a few times I’ve been left with an empty json file, so I created a DB table and shove it all in there now for safekeeping, updating according to timestamp. I also fetch tidal data from the Admiralty (quite useful where I live) and flot plot the lot (my wife says that 6 y-axes on a single graph is a bit much… she didn’t notice that ‘cloud’ and ‘humidity’ share one of them!)
Other tweaks I made include a wind direction arrow on the forecast list… more than happy to share the code if you want it. 🙂
@artlab, that looks very good, some amount of code went into that. i know openweather api is bit flaky but its free.
Hi Artlab!
Thanks for the help, I managed to do it.
How can I set PiHome Temperature Graps to see the values of the heat sensors?
Only the outside temperature is now on the graph.
Thanks
Pepe
If your node_ids are 20 and 21, it should already be displayed. If not:
Check that the data is there in the ‘messages_in’ table on the database for the node_id(s) you want to graph:
Make sure there is a ‘select’ statement (to create an array) in ‘chartlist.php’ for each of the node(s).
$query="select * from messages_in_view_24h where node_id= 21";
$result = $conn->query($query);
//create array of pairs of x and y values
while ($row = mysqli_fetch_assoc($result)) {
$ground_floor[] = array(strtotime($row['datetime']) * 1000, $row['payload']);
}
At the top of ‘chartfooter.php’, make sure there is a var(iable) for the node(s) and a line to do the ‘json_encode’:
var ground_floor = <?php echo json_encode($ground_floor); ?>;
Then check (just below that) that there is a line in the ‘dataset’ list to have that array of data plotted:
{label: "Ground Floor", data: ground_floor, color: "#DE000F"},
Let me know how you get on. 🙂
HI artlab!
I am Happy!!
Based on your instructions, you have been able to set the graps.
“Node id” had to change.
Thanks, You profesional !!!
I would have another question for you.
How can I rename things?
Pl: first_floor to “Nappali”
What are the files I need to overwrite?
Thanks!!! ? ? ?
Glad to be of help, Pepe. 🙂
To rename the zone on the ‘home.php’ list, change the ‘name’ field in the ‘zone’ table of the database.
To rename the label on the graph, look again at ‘chartfooter.php’ and change the ‘label:’ in the dataset list, e.g:
{label: "First Floor", data: first_floor, color: "#7D0096"},
would become:
{label: "Nappali", data: first_floor, color: "#7D0096"},
The label can be anything you want it to be.
* * * * * * * *
@Admin: I have looked at automating this and getting the flot labels & data lists from the database (zone name = label, node_id is the same as my array names, added fields for color, a flag to graph or not etc) – I tried a query + echo inside the flot dataset list… it made the whole system choke and freeze, yet if I echo the result of the query and copy&paste the result into the dataset list, it works perfectly.
Here’s the code, let me know if anything looks off to you :
var dataset_auto = [
<?php
//Get zone names and sensor nodes and graph colors
$query="select name, sensors_id, sensor_child_id, color from zone_view where type = 'Heating' AND graph = 1";
$results = $conn->query($query);
$count = mysqli_num_rows($results);
while ($row = mysqli_fetch_assoc($results)) {
if ((--$count) == 0) break;
echo "{label: \"" .$row['name']. "\", data: Sensor_" .$row['sensors_id']. "_" .$row['sensor_child_id']. ", color: \"#".$row['color']."\"}, \n";
}
?>
];
It yields this sort of thing:
{label: "Kitchen", data: Sensor_25_0, color: "#ff9b06" },
{label: "Utility", data: Sensor_26_0, color: "#e200d9" },
{label: "Bathroom", data: Sensor_101_1, color: "#b2b2b2" },
I’ve played with flot long enough to know it is full of the most irritating quirks and weirdness, so maybe it’s just one of those?
@artlab
Two array from charlist.php
$query="select * from messages_in_view_24h where node_id= 21";
$result = $conn->query($query);
//create array of pairs of x and y values
while ($row = mysqli_fetch_assoc($result)) {
$ground_floor[] = array(strtotime($row['datetime']) * 1000, $row['payload']);
}
//$arr_name='first_floor';
$query="select * from messages_in_view_24h where node_id= 20";
$result = $conn->query($query);
//create array of pairs of x and y values
while ($row = mysqli_fetch_assoc($result)) {
$first_floor[] = array(strtotime($row['datetime']) * 1000, $row['payload']);
}
————————————————————-
from chartfooter.php
var ground_floor = ;
var first_floor = ;
var weather_c = ;
var dataset = [
{label: "Ground Floor", data: ground_floor, color: "#DE000F"},
{label: "First Floor", data: first_floor, color: "#7D0096"},
{label: "Out Side", data: weather_c, color: "#009604"}
];
do we not need to modify array name in chartlist.php as well? how you can automate that? dataset works as you described but what about array name? can you share full rest if the code.
Ps: i tried this while back but then gave up on this so lets automate that if we can.
@Admin
I was working backwards from the graph (and got stuck there), so haven’t looked too hard at automating the construction of the queries/arrays yet, but since we can use PHP variables inside the queries, we should be able to generate what we need by querying the ‘zone’ table? Another couple of fields may be required there (for ‘color’ and a flag for whether to graph that zone or not) This is assuming that all sensors are attached or reporting to a zone (whether active or not).
I’ve got an eye on being able to turn data series on and off on the plot, so the flag is one possible way to do that.
I’m well aware that too many queries/datasets will impact on page load times badly (aw, poor little RasPi), in the past with flot I’ve used tickboxes on the plot page to turn data series on or off, then POST / SESSION variables (via ‘submit’ button) to include separate php pages that contain the actual queries.
If asked to plot a dataset formed from the json_encode of an array that doesn’t exist (as the page with that query wasn’t called by ‘include’), flot just politely shrugs and moves on. It’s a bit of a messy way to do it, but it’s useful if displaying weeks of data and multiple sensors.
Other things I’m looking at for flot… a date/time picker to select the time the plot covers and probably ‘zoom on selection’ which works quite well (but can be annoying on touchscreens).
I’ll upload my entire PiHome to github once I’ve cleaned it up a bit (I’ve made so many barbaric cludegy hacks that I’m too embarrassed to share).
I’ve got a second server (with plenty of grunt) running a mirror of my PiHome now, so I’ll try and figure out what caused the lock-up earlier with the query-generated dataset I tried before and take it (backwards) from there. 🙂