Introduction: Raspberry PI With DS18b20 Web Server PHP - Remote Temperature Measurement

About: Software, electronics, do-it-yourself

How to make remote temperature measurement using Raspberry PI, DS18B20, PHP and PostgreSQL. This projection will show you how to easily make a temperature logger using the above technology. The entire temperature logger will be made using the PostgreSQL database. I will also show the example of a working online temperature logger on my website.

This article can also see here:


Raspberry PI with DS18b20 web server PHP - Remote temperature measurement

Step 1: Components

Step 2: Requirements

In this project we will need installed:

  • Apache2
  • PHP
  • PHP PDO
  • PHP PostgreSQL

Install the apache2 package by typing the following command in to the Terminal: sudo apt-get update sudo apt-get install apache2 Then we install PHP. sudo apt-get install php5 libapache2-mod-php5 Install the PostgreSQL. sudo apt-get install php5-pgsql

Step 3: Connection of the Temperature Sensor

The DS18B20 sensors can be connected in parallel. The resistor 4.7k is used as a pullup for the data-line, and is required to keep the data transfer stable. All sensors should share the same pins, and you only need one 4.7K resistor for all of them.

NOTE: In newer versions of the system, add the following entry to /boot/config.txt and restart the Raspberry PI.

dtoverlay=w1-gpio,gpiopin=4 With this command we can check the attached devices for one wire. cat /sys/bus/w1/devices/w1_bus_master1/w1_master_slaves To read the temperature from sensor, type the following command, replace device_id with your device identifier. cat /sys/bus/w1/devices/[device_id]/w1_slave

Step 4: Database Creation

Now create a simple database containing only two tables.Below the table in which we will store the connected devices.

FieldDescription
nameFriendly name
dev_idDevice identifier
	CREATE TABLE w1_devices
	(
	  w1_devices_id serial NOT NULL,
	  name character varying(128) NOT NULL, -- Friendly name
	  dev_id character varying(64) NOT NULL, -- Device identifier
	  CONSTRAINT w1_devices_pkey PRIMARY KEY (w1_devices_id),
	  CONSTRAINT w1_devices_dev_id_key UNIQUE (dev_id)
	)

Table containing temperature measurements.

FieldDescription
date_insertMeasurement time
w1_devices_idRow identifier from table "w1_devices"
temperatureThe value of the measured temperature
date_checkTime of the last measurement.
	CREATE TABLE temperature
	(
	  temperature_id serial NOT NULL,
	  date_insert timestamp with time zone NOT NULL DEFAULT now(),
	  w1_devices_id integer NOT NULL,
	  temperature numeric(10,2),
	  date_check timestamp with time zone,
	  CONSTRAINT temperature_pkey PRIMARY KEY (temperature_id),
	  CONSTRAINT temperature_w1_devices_id_fkey FOREIGN KEY (w1_devices_id)
	      REFERENCES w1_devices (w1_devices_id) MATCH SIMPLE
	      ON UPDATE NO ACTION ON DELETE NO ACTION
	)

Step 5: Script in PHP

Below is a script that will be executed every minute, via cron. This script measures the temperature of the sensors (DS18B20), then compares the value of the measurement to the previous value. If the difference is greater than 0.1 degrees Celsius,it inserts a new record into the table "temperature". If the difference is less than 0.1 degree celsius. This does the update of the last measurement by changing the value of "date_check". I put this file in /var/www/html/

Before using these scripts, you need to configure your connection to the database server. I use an external database on my server, but you can also use a local database on the Raspberry PI.

	$dbname='';
	$host='';
	$dbuser='';
	$dbpass='';
File temp.php
<?php
	error_reporting(E_ALL);
	ini_set('display_errors', 1);

	$dbname='';
	$host='';
	$dbuser='';
	$dbpass='';
	try {
		$db = new PDO("pgsql:dbname=$dbname;host=$host", $dbuser, $dbpass);
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}catch(PDOException $e){
    	echo "ERROR: " . $e->getMessage();
	}
	
	//----------------------------------
	$str = file_get_contents('/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves');
	$dev_ds18b20 = preg_split("/\\r\\n|\\r|\\n/", $str);
	
	
	foreach( $dev_ds18b20 as $val ){
		if( $val!='' ){
			//echo "DS18B20: $val<br>\r\n";
			$temp_path = "/sys/bus/w1/devices/$val/w1_slave";
			$str = file_get_contents($temp_path);
			if( preg_match('|t\=([0-9]+)|mi', $str, $m) ){
				$temp = $m[1] / 1000;
				//echo "temp=$temp<br>\r\n";
				SaveMeasurement( $db, $val, $temp);
			}
		}
	}
	//----------------------------------
	
	function SaveMeasurement($db, $dev_id, $temp){
		try {
			$sql = $db->query ("SELECT * FROM w1_devices WHERE dev_id='$dev_id'");
			$result = $sql->fetch( PDO::FETCH_ASSOC );
			if( $result===false ){
		    	die('You must first define the device: ');
		    }else{
		    	$sql = $db->query ("SELECT * FROM temperature WHERE w1_devices_id='$result[w1_devices_id]' ORDER BY date_insert DESC LIMIT 1");
				$result = $sql->fetch( PDO::FETCH_ASSOC );
				$ins = true;
				if( $result!==false && abs($result['temperature'] - $temp) < 0.1 ){
					echo abs($result['temperature'] - $temp);
					$ins = false;
				}
				
				if( $ins ){
					$sql = "INSERT INTO temperature(w1_devices_id, temperature) VALUES(:w1_devices_id, :temperature)";
			    	$statement = $db->prepare($sql);
					$statement->bindValue(':w1_devices_id', $result['w1_devices_id']);
					$statement->bindValue(':temperature', $temp);
					$statement->execute();
					$statement->closeCursor();
				}else{
					$sql = "UPDATE temperature SET date_check=now() WHERE temperature_id=:temperature_id";
			    	$statement = $db->prepare($sql);
					$statement->bindValue(':temperature_id', $result['temperature_id']);
					$statement->execute();
					$statement->closeCursor();	
				}
		    	
		    }
		}catch(PDOException $e){
	    	echo "ERROR: " . $e->getMessage();
		}
	}
?>
Now we will create a shell script. cd /var/www/html/ nano cron_temp.sh chmod +x cron_temp.sh File cron_temp.sh
php -f /var/www/html/temp.php
Then we add this file to corn. crontab -e We add this line and save. * * * * * /var/www/html/cron_temp.sh Saving the results of temperature measurement every minute should already work. Now display the results from the table "temperature".
For this purpose we write another two scripts.
File ds18b20.php
<?php
	error_reporting(E_ALL);
	ini_set('display_errors', 1);

	echo "time: " . time() . "\r\n<br>";

	$str = file_get_contents('/sys/bus/w1/devices/w1_bus_master1/w1_master_slaves');
	$dev_ds18b20 = preg_split("/\\r\\n|\\r|\\n/", $str);
	
	
	foreach( $dev_ds18b20 as $val ){
		if( $val!='' ){
			echo "DS18B20: $val<br>\r\n";
			$temp_path = "/sys/bus/w1/devices/$val/w1_slave";
			$str = file_get_contents($temp_path);
			if( preg_match('|t\=([0-9]+)|mi', $str, $m) ){
				$temp = $m[1] / 1000;
				echo "temp=$temp<br>\r\n";
			}
		}
	}
	
	$dbname='';
	$host='';
	$dbuser='';
	$dbpass='';
	try {
		$db = new PDO("pgsql:dbname=$dbname;host=$host", $dbuser, $dbpass);
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}catch(PDOException $e){
    	echo "ERROR: " . $e->getMessage();
	}
	
	
	?><div style="background-color: #a0a0a0; vertical-align: bottom;"><?php
	$sql = "
			SELECT * FROM (
				SELECT * FROM temperature ORDER BY date_insert DESC LIMIT 35
			) AS T ORDER BY date_insert
			";
    foreach ($db->query($sql) as $row) {
        ?><div style="display:inline-block; margin-right: 1px; background-color: #66b3ff; vertical-align: bottom; width: 50px; height: <?php echo 2 * $row['temperature']; ?>px;"><?php echo $row['temperature']; ?></div><?php

    }
	
?></div>
To automatically refresh the results every second, we use Jquery and AJAX.
File index.php
<?php
	error_reporting(E_ALL);
	ini_set('display_errors', 1);
	
	$dbname='';
	$host='';
	$dbuser='';
	$dbpass='';
	try {
		$db = new PDO("pgsql:dbname=$dbname;host=$host", $dbuser, $dbpass);
		$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}catch(PDOException $e){
    	echo "ERROR: " . $e->getMessage();
	}
	
?><html>
  <head>
    <title><?php echo exec('hostname'); ?></title>
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
	<script type="text/javascript">

		function check(){
			$.get( "ds18b20.php", function( data ) {
				  $( "#result" ).html( data );
				  
				});
		}
		
	</script>
	<script type="text/javascript">
	<!--
		setInterval( "check()" ,1000);
	//-->
	</script>
    
    
  </head>
  <body>

  <div id="result"></div>

  </body>
</html>
Download source code: all-files.zip

Step 6: The End

Below the table with temperature measurements. The sensor is mounted in my living room and the temperature update is one minute.

Check the current temperature