Making a temperature monitor with Spark Core, and a bit of PHP

I have recently started making biltong at home, and coincidentally also received a Spark Core dev kit from http://spark.io as well. I then decided that a quick and simple biltong monitor would be a good starter project, so set out to do just that.

I grabbed this diagram as a starter and built a simple Spark Core temperature sensor (thermometer), straight from the Spark docs

 

breadboard-temp-sensor

 

As soon as your sensor is built, you can then proceed to the Spark Online IDE and flash some code to it

#include <math.h>

// -----------------
// Read temperature
// -----------------

// Create a variable that will store the temperature value
int temperature = 0;
double voltage = 0.0;
double tempinC = 0.0;

char vStr[10];
char tStr[10];

void setup()
{
  // Register a Spark variable here
  Spark.variable("temperature", &temperature, INT);
  Spark.variable("voltage", &voltage, DOUBLE);
  Spark.variable("tempinC", &tempinC, DOUBLE);

  // Connect the temperature sensor to A7 and configure it to be an input
  pinMode(A7, INPUT);
}

void loop()
{
  // Keep reading the temperature so when we make an API
  // call to read its value, we have the latest one
  temperature = analogRead(A7);
  voltage = (temperature * 3.3)/4095;
  tempinC = (voltage - 0.5)*100;

}

/**
 * The API request will look something like this:
 * GET /v1/devices/{DEVICE_ID}/temperature
 * # EXAMPLE REQUEST IN TERMINAL
 * # Core ID is 0123456789abcdef
 * # Your access token is 123412341234
 * curl -G https://api.spark.io/v1/devices/0123456789abcdef/tempinC \
 * -d access_token=123412341234
 */

You should then be able to test it out by sending some HTTP requests to it. Generally, I would use Curl from http://curl.haxx.se, but I am doing some Win8.1 dev and didn’t want to bother with it, so I simply used http://www.hurl.it/ to fiddle with my Spark core.

A couple of things that you need to do to set up with Hurl.it is that you need a copy of your access_token and deviceID from your Spark Core. These are both available in your online IDE sidebar.

Set the parameters in Hurl.it as access_token and then whatever you set your code vars as. In the above example it will be “tempinC”, “voltage”, or “temperature”. We will mostly be concentrating on tempinC though.

Set your URL as

https://api.spark.io/v1/devices/

with your device ID as part of the URL. You may now execute the request and it should return some JSON from your Spark core!

Right, now that we know that it works and is sending us back a valid temperature, we can proceed with a bit of PHP.

Data is not really useful until you do something with it, so let’s build a very quick and VERY dirty PHP/MySQL app to house our data. PLEASE NOTE that this code is awful, so make it better…

First up, the index.php file:

<?php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'https://api.spark.io/v1/devices/1234567890abcdef/tempinC/?access_token=12470717420914290127401274',
    CURLOPT_USERAGENT => 'paulscott.co.za'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

$data = json_decode($resp);
$temp = $data->result;
echo "<h3>Current temperature is: " . $temp . " C</h3>";

// MySQL stuff... sigh
$dbhost = 'localhost:3036';
$dbuser = 'username';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO biltong '.
       '(temperature, humidity, currtime) '.
       'VALUES ( '.$temp.', "0", NOW() )';

mysql_select_db('sparkdata');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not enter data: ' . mysql_error());
}
//echo "Entered data successfully\n";
mysql_close($conn);

// check out the nifty graph...
echo '<h3>Temperatures in the Biltong maker over time</h3> <img src="graph.php" />';

This basically grabs the data by making a cURL request, then adds it to a MySQL database. Dead simple.
Next we want the file that this file refers to (graph.php)

<?php
include('phpgraphlib/phpgraphlib.php');
$graph = new PHPGraphLib(1100,700); 
$dataArray = array();

$dbhost = 'localhost:3036';
$dbuser = 'username';
$dbpass = 'password';

$link = mysql_connect($dbhost, $dbuser, $dbpass)
   or die('Could not connect: ' . mysql_error());
     
mysql_select_db('sparkdata') or die('Could not select database');
  
$dataArray=array();

//get data from database
$sql = "SELECT temperature, id, currtime FROM biltong LIMIT 150";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());
if ($result) {
  while ($row = mysql_fetch_assoc($result)) {
      $temperature = $row["temperature"];
      $count = $row["currtime"];
      //add to data areray
      $dataArray[$count] = $temperature;
  }
}
//configure graph
$graph->addData($dataArray);
$graph->setTitle("Temperature");
$graph->setGradient("lime", "green");
$graph->setBarOutlineColor("black");
$graph->setBars(false);
$graph->setLine(true);
$graph->createGraph();
//echo $sql;
?>

Done! You will also need PHPGraphLib from http://www.ebrueggeman.com/phpgraphlib

Now, whenever a request is sent to the index file, it will grab the data and graph it. You can add the curl request to a cron job too and get regular data etc as well.

As I say, this is a simple example, but demonstrates how easy it is to start building some very cool sensors with Spark Core!

Liked this post? Follow this blog to get more.