Create a temperature logger

This miniproject illustrates how to create a Web-enabled temperature logger

written by Sergio Tanzilli

To build our temperature logger we'll show how to install and use on our FOX Board G20 the following items:

Requirements

Hardware requirements

To build this logger we need a FOX Board G20 wired to a Dallas Thermal Sensor. To see how to read this article: Using 1-wire Dallas DS18B20 thermal sensor

Software requirements

The Python interpreter usually is already installed. If not please read how to install it here

The SQLite support for Python is provided by the module Pysqlite2 that can be install from the Debian standard repository package typing:

debarm:~# apt-get update
debarm:~# apt-get install python-pysqlite2

The PHP interpreter usually is already installed. If not please read how to install it here

The SQLite support for PHP is not installed by default to install it type:

debarm:~# apt-get update
debarm:~# apt-get install php5-sqlite
...
debarm:~# /etc/init.d/lighttpd restart
Stopping web server: lighttpd.                                                  
Starting web server: lighttpd.

Cron is the already installed

Lighttpd web server is alredy installed and configured to publish the pages and PHP scripts stored in the /var/www directory

FusionCharts Free is downloadable from this URL http://www.fusioncharts.com/free. Download and unzip it on your PC, then create a directory called FusionCharts in /var/www in your FOX typing:

debarm:~# cd /var/www
debarm:/var/www# mkdir FusionCharts

then copy the contens of Charts directory on your PC in this new directory (see how to copy files from your PC to the FOX on this article). The .swf file you are copying contents the different type of charts you can visualize. Thake a look to the chart gallery available clicking on the following icon:

Sample reading

The simple Python program listed below get the temperature value from the thermal sensor and add a record to the SQLite file /var/www/temperature.sqlite storing date, time and value in Celsius degrees then exits.

File: http://foxg20.acmesystems.it/download/examples/tlogger.py -

#!/usr/bin/python
import time
import fox
from pysqlite2 import dbapi2 as sqlite
 
 
# Read the temperature value from the thermal sensor identified 
# by the id 0000027f8f99. This is a unique ID available on
# /sys/bus/w1/devices  
 
sensor = fox.DS18B20("0000027f8f99")
sample = sensor.getTemp()
 
# Insert a new record for this sample on the SQLite database
 
connection = sqlite.connect('/var/www/temperatures.sqlite')
cursor = connection.cursor()
cursor.execute('CREATE TABLE IF NOT EXISTS samples (id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT, time TEXT, value FLOAT)')
cursor.execute('INSERT INTO samples VALUES (null, date("now","localtime"),time("now","localtime"),' + "%.2f" % sample + ')')
connection.commit()
 
print "Temp=%.2f C" % (sensor.getTemp())

To install it type:

debarm:~# cd /var/www
debarm:/var/www# wget http://foxg20.acmesystems.it/download/examples/tlogger.py
...
debarm:/var/www# wget http://foxg20.acmesystems.it/download/examples/fox.py
...
debarm:/var/www# chmod +x tlogger.py

Edit the line:

sensor = fox.DS18B20("0000027f8f99")

and change the ID code 0000027f8f99 with the ID code of your thermal sensor. You can read it typing:

debarm:/var/www# ls /sys/bus/w1/devices/                                                                         
28-0000027f8f99  w1 bus master

To try manually the program type:

debarm:/var/www# ./tlogger.py
Temp=21.20 C

The SQLite file called temperatures.sqlite is created.

To read this file it is possible to use the SQLite command line interface. To install it type:

debarm:~# apt-get update
debarm:~# apt-get install sqlite3

then read the readings typing:

debarm:~# sqlite3 temperatures.sqlite
SQLite version 3.5.9
Enter ".help" for instructions
sqlite>

Insert an SQL query typing:

sqlite>select * from samples;
1|2010-05-05|10:20:24|24.0
2|2010-05-05|10:21:41|24.0
sqlite>.quit
debarm:~#

More info about the SQLite command line interface is available here.

Schedule the sampling with Cron

To read the temperatures at regular intervals we can use the utility Cron. This utility uses a table called Crontab (CRON TABle) to schedule events to run at specified times.

A crontab file has five fields for specifying day, date and time followed by the command to be run at that interval.

*     *     *   *    *        command to be executed
-     -     -   -    -
|     |     |   |    |
|     |     |   |    +----- day of week (0 - 6) (Sunday=0)
|     |     |   +------- month (1 - 12)
|     |     +--------- day of        month (1 - 31)
|     +----------- hour (0 - 23)
+------------- min (0 - 59)

To edit the Cron table type:

debarm:/var/www# crontab -e

and insert the following configuration:

0 * * * * /var/www/tlogger.py

then save and exit and exit from the text editor.

Our program /var/www/tlogger.py will be called each time the minutes values of the system clock become equal to 0, in other words each hour.

To learn more about Cron and Crontab read this quick reference http://adminschoice.com/crontab-quick-reference.

Read the temperature log via web

Using the PHP language it is possible to generate on-the-fly web views of the temperatures read as shown below:

This is the PHP source used to generate this web page.

File: http://foxg20.acmesystems.it/download/examples/tlogger_php -

<html>
<head>
<title>Temperature logger web interface</title>
</head>
<body>
<h1>Temperature logger</h1>
 
<table border="1"> 
<tr><th>Date available</th><th>Details</th><th>Chart</th><tr>
 
<tr>
 
<!-- Create the left column contents with the list dates logged  -->
 
<td valign="top">
<?php
	try {
		/*** connect to SQLite database ***/
		$dbh = new PDO("sqlite:/var/www/temperatures.sqlite");
 
		/*** The SQL SELECT statement ***/
		$sql = "SELECT date FROM samples GROUP BY date";
 
		foreach ($dbh->query($sql) as $row) {
			echo "<a href='?cmd=list&date=$row[date]'>$row[date]</a><br/>";
		}
		$dbh = null;
	}
	catch(PDOException $e)
	{
		echo $e->getMessage();
	}
?>
</td>
 
 
<?php
	if (isset($_GET["cmd"])) {
		if ($_GET["cmd"]=="list") {
 
			// Create the middle column content with the temperature sample
 
			echo "<td valign='top'>";
			try {
				/*** connect to SQLite database ***/
				$dbh = new PDO("sqlite:/var/www/temperatures.sqlite");
 
				/*** The SQL SELECT statement ***/
				$sql = "SELECT * FROM samples WHERE date LIKE '$_GET[date]%'";
 
				echo "<table border='1'>";
				echo "<tr>";
				echo "<th>Date</th><th>Time</th><th>Temp</th>";
				echo "</tr>";
 
				foreach ($dbh->query($sql) as $row) {
					echo "<tr>";
					echo "<td>" . $row['date'] . "</td><td>" . $row['time'] . "</td><td>" . $row['value'] . "</td>";
					echo "</tr>";
				}
				echo "</table>";
 
				$dbh = null;
			}
			catch(PDOException $e)
			{
				echo $e->getMessage();
			}
 
			// Generates the tmp/data.xml file that will be read by the FusionChart component	
 
			try {
 
				$handle = fopen("/tmp/data.xml", "w");	
				/*** connect to SQLite database ***/
				$dbh = new PDO("sqlite:/var/www/temperatures.sqlite");
 
				/*** The SQL SELECT statement ***/
				$sql = "SELECT * FROM samples WHERE date LIKE '$_GET[date]%'";
 
				fprintf($handle,"<graph xAxisName='Time' yAxisName='Temperature' showNames='1' decimalPrecision='1' formatNumberScale='0'>\n");
 
				foreach ($dbh->query($sql) as $row) {
					fprintf($handle,"<set name='" . substr($row['time'],0,2) . "' value='" . $row['value'] . "' />\n");
					// echo "<td>" . $row['date'] . "</td><td>" . $row['time'] . "</td><td>" . $row['value'] . "</td>";
				}
				fprintf($handle,"</graph>\n");
				$dbh = null;
				fclose($handle);	
			}
			catch(PDOException $e)
			{
				echo $e->getMessage();
			}
			echo "</td>";
 
			echo "<td>";
 
			// FusionChart component
			?>
 
			<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase=http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="640" height="360" id="Column3D" >
				<param name="movie" value="FusionCharts/FCF_Line.swf" />
				<param name="FlashVars" value="&dataURL=tmp/data.xml&chartWidth=640&chartHeight=360">
				<param name="quality" value="high" />
				<embed src="FusionCharts/FCF_Line.swf" flashVars="&dataURL=tmp/data.xml&chartWidth=640&chartHeight=360" quality="high" width="640" height="360" name="Column3D" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />
			</object>
			<?
			echo "</td>";
		}
	}
?>
</tr>
</table>
</body>
</html>
 

To try it type:

debarm:~# cd /var/www
debarm:/var/www# wget http://foxg20.acmesystems.it/download/examples/tlogger_php
debarm:/var/www# mv tlogger_php tlogger.php

Now create a soft link to the /tmp directory used by this script to generare a temporany xml file used by the Flowchart component inside the html page to generate the temperature chart.

debarm:~# cd /var/www
debarm:/var/www# ln -s /tmp tmp

Now open your brower to this URL: http://fox_ip/tlogger.php to see the web interface.

What do you need to do this example


FOX Board G20 combo box

Main features

  • FOX Board G20 with Netus G20 and Netus PS1 modules (FOXG20, NETUSG20, NETUSPS1)
  • Wall mounted switching power supply at 5VDC-1A (PS5V1A)
  • Debug Port Interface (DPI)
  • 2GB bootable microSD with preinstalled Debian Linux (DEBM2G)
  • CR1220 3V RTC Lithium Battery
  • USB microSD card reader
  • MiniUSB cable
  • Transparent plastic enclosure (FOXCASE)

  • Price: EUR 185
  • Notes: This article replace the previous COMBO-1 kit
  • Code: COMBO-2
  • More info...

1-wire Dallas DS18B20 thermal sensor
The DS18B20 digital thermometer provides 9-bit to 12-bit Celsius temperature measurements.

A 4.7 KOhm is provided with this sensor.

 
miniproject/temperature_logger.txt · Last modified: 2010/05/06 19:08 by tanzox
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki