Storing temperature data in postgresql

An arduino board is running as a web server serving temperatures read out from some DS18B20 sensors. The data are stored in a postgresql database. The data table has been defined as:

create table temps(
   id serial primary key,
   termid integer,
   temp double presicion not null,
   sensoraddr character varying(20),
   datetime  timestamp with time zone default now()

A php-script is set upp to poll the arduino and fetch data. It sends data as json, described here.

$server=""; // Must be set up to match the arduino's IP.
$pgserver='localhost';   // postgres server
$username='.....'; // postgres user name
$password='.....'; // postgres password
    $dbh = new PDO($connectstring, $username, $password);
      $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  catch(PDOException $e){
    exit( "

Cannot connect - $message

$fp = fsockopen($server, 80, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)
} else {
    $out = "GET /json HTTP/1.1\r\n";
    $out .= "Host: $server\r\n";
    $out .= "Connection: Close\r\n\r\n";
    fwrite($fp, $out);
    while (!feof($fp)) {
        $data .= fgets($fp, 128);
$data=split("\n",$data); // cuts of the headers
$sql="insert into temps(temp,sensoraddr)values(?,?)";

This can be trigged from some event, or it may be run periodically. To make it run once every 15 minutes, save the php script as ‘fetchtemp.php’ and make the following shell-script in the same directory:

while true; do
php fetchtemp.php
sleep 900

(or call it from cron or any other scheduler)

I have also a system for presenting the data as a svg-graph.

This entry was posted in arduino, php, sql. Bookmark the permalink.