Temp change on website

Hi,

Is it possible to send live temperature readings directly to a webpage?

  1. The method i want to use is outputting the readings into an excel table, and use PHP to display the readings in the website. Can this be done?

  2. Also, i want a thermometer image to go up an down depending on the temperature readings. What software would i need to do this?

Hi, yes it is possible, depending what you mean by “live”.

I have done something similar recently using an esp8266 wifi module, programmed using the Arduino IDE, and an sht21 temp/humidity sensor, which sends its data to a website every 15 minutes.

There are various web services available that will accept and display data from sensors in the form of graphs or other symbols, and many are free. But I decided to take the opportunity to learn more by doing that stuff myself. This gave me the opportunity to learn some PHP, mySQL and SVG graphics, and I am pleased with the results so far.

I have plans to make multiple sensors like this including an outdoor module to measure wind speed and direction as well as temp, humidity, barometric pressure, light levels and so on.

Screenshot_2015-12-25-21-49-08.png

Paul

Would it be possible to send information every second or millisecond?

Could you explain how you completed your project please.

Also i have another question. When building a website, is HTML used for the images, and PHP for the dynamically changing information?

With the techniques i am using, I think updating every second would be difficult. Certainly not every millisecond. But why would you need temperature updates so frequently?

I will post some code for you later. There is an Arduino sketch which reads the sensor, connects to wifi and sends the data using the http GET command with a parameter containing the new sensor reading. A php script on the server responds to to get command, picks up the sensor reading and stores it in a database table using an sql INSERT command. A second php script creates a web page showing the latest sensor readings in a table and and gives links to pages with graphs for each sensor. Another php script creates the graph pages using SVG commands.

The php scripts create html files when needed. When the “client” (your browser or the Arduino sketch) accesses the script, the php code runs on the server and creates an html file which may also contain some svg commands to draw the graphs. This html file is sent back to thr client to be displayed.

Thank you!!!

I need to put my information into a website, with the sections shown in the screenshots.

Do i need to make the website using HTML/CSS then use PHP within the code to change the numerical values?

SHOT.jpg

Yes, that's the way i did it.

If you do not need to draw graphs or keep any history, you could get the Arduino to calculate the average temp and send that to the site with the current temp. This makes the server code easier. The values can be stored in a file ready for the php code to format onto the web page.

There are many ways to approach this project and this is only one of them. For example, an Arduino can act as the web server. This was not an option for me because my ISP blocks access to locally hosted servers.

On your web page, do you need the temperature reading to update itself every second, or just when Refresh is pressed? If so, you may need the write some javascript to make the page refresh itself.

PaulRB:
I will post some code for you later. There is an Arduino sketch which reads the sensor, connects to wifi and sends the data using the http GET command

Could you send that code please?
Also, what software did you use for the graph?

Ok, I'll post the code hopefully tomorrow evening.

The graphs are drawn with SVG (Scalable Vector Graphics).

Here is the Arduino sketch:

/* 
 *  WiFi Indoor Sensor
 *  By PaulRB Nov 2015
 *  ESP-01 Sketch
 */

#include <Wire.h>
#include "SparkFunHTU21D.h"
#include <SFE_BMP180.h>
#include <ESP8266WiFi.h>

const float e = 2.71828;

const char ssid[]     = "xyz";
const char password[] = "xyz";
const char host[] = "www.xyz.co.uk";

//Create an instance of the sensor objects
HTU21D humiditySensor;
SFE_BMP180 pressureSensor;
// Use WiFiClient class to create TCP connections
WiFiClient client;

void setup()
{
  Serial.begin(115200);

  Wire.begin(2, 0);
  humiditySensor.begin();
  pressureSensor.begin();

  Serial.println();
  Serial.print("Connecting to ");
  Serial.print(ssid);
  
  WiFi.begin(ssid, password);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("OK");
  Serial.print("WiFi connected, IP address: ");
  Serial.println(WiFi.localIP());
}

void loop()
{

  unsigned long startTime = millis();
  
  float humidityNow = humiditySensor.readHumidity();
  float temperatureNow = humiditySensor.readTemperature();
  float absoluteHumidityNow = (6.112 * pow(e,(17.67 * temperatureNow)/(temperatureNow + 243.5)) * humidityNow * 2.1674) / (273.15 + temperatureNow);
  double temperature2Now;
  delay(pressureSensor.startTemperature());
  pressureSensor.getTemperature(temperature2Now);
  double pressureNow;
  delay(pressureSensor.startPressure(1));
  pressureSensor.getPressure(pressureNow, temperature2Now);


  Serial.print("New sensor readings: Temperature:");
  Serial.print(temperatureNow, 1);
  Serial.print("C");
  Serial.print(" Humidity:");
  Serial.print(humidityNow, 1);
  Serial.print("% = ");
  Serial.print(absoluteHumidityNow, 1);
  Serial.print("g/m3");
  Serial.print(" Pressure:");
  Serial.print(pressureNow, 1);
  Serial.print("Pa");
  Serial.print(" Temp2:");
  Serial.print(temperature2Now, 1);
  Serial.print("C");
  Serial.println();

  Serial.println();
  Serial.print("connecting to ");
  Serial.println(host);
  
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
  
  if (!sendSensorUpdate("T2", temperatureNow, false)) {
    return;
  }

  if (!sendSensorUpdate("H2", humidityNow, false)) {
    return;
  }
    
  if (!sendSensorUpdate("A2", absoluteHumidityNow, false)) {
    return;
  }

  if (!sendSensorUpdate("P1", pressureNow, true)) {
    return;
  }
  
  Serial.println();
  Serial.println("closing connection");

  Serial.print("Total time: ");
  Serial.println( millis() - startTime);

  Serial.println("Sleeping...!");
  delay(900000UL); // 15 mins
  Serial.println("Awake!");
}

boolean sendSensorUpdate(char* sensorName, double sensorValue, boolean closeConnection) {

  unsigned long startTime = millis();

  // We now create a URI for the request
  String url = "/script.php";
  url += "?sensor=";
  url += sensorName;
  url += "&value=";
  url += sensorValue;
  
  Serial.print("Requesting URL: ");
  Serial.println(url);
  
  // This will send the request to the server
  if (closeConnection) {
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" + 
                 "Connection: close\r\n\r\n");
  }
  else {
      client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                   "Host: " + host + "\r\n\r\n" );
  }

  while(!client.available()) {
    if (millis() - startTime > 30000UL) {
      Serial.println("request failed");
      return false;
    }
    delay(100);
  }
  
  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }
  return true;
}

Here is the PHP script that responds to the GET requests from the Arduino sketch and stores the values into the database:

<?php
$sensor=$_GET["sensor"];
$value=$_GET["value"];
$servername = "www.xyz.co.uk";
$username = "xyz";
$password = "xyz";
$dbname = "xyz";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$stmt = $conn->prepare("INSERT INTO xyz_sensors (sensor_name, sensor_value) VALUES (?, ?)");
$stmt->bind_param("sd", $sensor, $value);
$stmt->execute();
echo "New record created successfully";

$conn->close();
?>

Here is the php script that creates the web page showing the table of the sensors and their current values, with links to the graph pages:

<!DOCTYPE html>
<html>
<body>

<h1>Sensors Page</h1>

<table border=1>
<tr><th>Sensor</th><th>Value</th><th>Time</th></tr>

<?php 
$servername = "www.xyz.co.uk";
$username = "xyz";
$password = "xyz";
$dbname = "xyz";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    echo "Sorry, the website is experiencing problems: " . $conn->connect_error();
    exit;
}

$sql = "SELECT   s.sensor_time, s.sensor_name, s.sensor_value, i.sensor_desc, i.sensor_units
        FROM     xyz_sensors s
        JOIN     (   SELECT   sensor_name, MAX(sensor_time) AS max_time
                     FROM     xyz_sensors
                     GROUP BY sensor_name) AS m
        ON       m.sensor_name = s.sensor_name 
        AND      m.max_time = s.sensor_time
        JOIN     sensor_info i
        ON       i.sensor_name = s.sensor_name
        ORDER BY s.sensor_name;";

if (!$result = $conn->query($sql)) {
    echo "Sorry, the website is experiencing problems.";
    exit;
}

// List sensors, values and last updates with links to graphs
while ($reading = $result->fetch_assoc()) {
    echo "<tr><td><a href='http://$servername/graph.php?sensor=" . $reading['sensor_name'] . "&view=1'>" . $reading['sensor_desc'] . "</a></td>";
    echo "<td>" . $reading['sensor_value'] . $reading['sensor_units'] . "</td><td>" . $reading['sensor_time'] . "</td></tr>";
}

$result->free();
$conn->close();
?>

</table>

</body>
</html>

And finally here is the php script that creates the graphs:

<!DOCTYPE html>
<html>
<body>

<?php 
// Sensor Graph Script
// PaulRB
// Nov 2015

$sensor = $_GET["sensor"];
$view = $_GET["view"];
$servername = "www.xyz.co.uk";
$username = "xyz";
$password = "xyz";
$dbname = "xyz";
$colours = array("magenta", "blue", "red", "yellow", "cyan", "black");

// Connect to database
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    echo "Sorry, the website is experiencing problems: " . $conn->connect_error();
    exit;
}

// Get sensor description and min & max values to be plotted
$sql = "SELECT   i.sensor_units,
                 MIN(s.sensor_time) AS min_time, MAX(s.sensor_time) AS max_time,
                 MIN(s.sensor_value) AS min_value, MAX(s.sensor_value) AS max_value
        FROM     xyz_sensors s
        JOIN     sensor_info i ON i.sensor_name = s.sensor_name
        WHERE    s.sensor_name like '$sensor%'
        AND      s.sensor_time > NOW() - INTERVAL $view DAY
        GROUP BY i.sensor_units;";

if (!$result = $conn->query($sql)) {
    echo "Sorry, the website is experiencing problems.\n";
    exit;
}

$reading = $result->fetch_assoc();
$min_value = $reading['min_value'];
$max_value = $reading['max_value'];
$min_time = strtotime($reading['min_time']);
$max_time = strtotime($reading['max_time']);
$units = $reading['sensor_units'];

echo "<h1>Sensor Graphs ";
echo "<a href='http://$servername/graph.php?sensor=$sensor&view=1'>24 hrs</a> ";
echo "<a href='http://$servername/graph.php?sensor=$sensor&view=7'>7 days</a> ";
$sensor_type = substr($sensor,0,1);
echo "<a href='http://$servername/graph.php?sensor=$sensor_type&view=$view'>compare</a> ";
echo "<a href='http://$servername/sensors.php'>index</a> ";
echo "</h1>";

// Choose scale for vertial axis (sensor reading)
if ($max_value - $min_value > 100) $value_scale = 10;
elseif ($max_value - $min_value > 30) $value_scale = 5;
elseif ($max_value - $min_value > 10) $value_scale = 2.5;
elseif ($max_value - $min_value > 5) $value_scale = 1;
elseif ($max_value - $min_value > 3) $value_scale = 0.5;
elseif ($max_value - $min_value > 1) $value_scale = 0.25;
elseif ($max_value - $min_value > 0.5) $value_scale = 0.1;
else $value_scale = 0.05;

$min_value = $value_scale * floor($min_value / $value_scale);
$max_value = $value_scale * ceil($max_value / $value_scale);

// Choose scale for horizontal axis (time)
if ($view < 7) $time_scale = 2 * 60 * 60;
else $time_scale = 12 * 60 * 60;

echo "<svg width=100% viewBox='0 0 1000 500' >\n";

// Draw graph
echo "<rect x=0 y=0 width=1000 height=500 stroke=green fill=none stroke-width=2 />\n";

// draw vertical axis (sensor values)
for ($y = $min_value; $y < $max_value; $y +=$value_scale) {
    $yv = round(500 - 500 * ($y - $min_value) / ($max_value - $min_value), 0);
    echo "<line stroke=green stroke-dasharray='5,5' x1=0 y1=$yv x2=1000 y2=$yv />\n";
    echo "<text fill=green x=0 y=$yv >$y$units</text>\n";
}

// Draw horizonal axis (time)
for ($x = ceil($min_time / $time_scale) * $time_scale; $x < $max_time; $x += $time_scale) {
    $xv = round(1000 * ($x - $min_time) / ($max_time - $min_time), 0);
    echo "<line stroke=green stroke-dasharray='5,5' x1=$xv y1=0 x2=$xv y2=500 />\n";
    echo "<text fill=green x=$xv y=500 >";
    if ($x % 86400 != 0) echo date("H:i", $x); else echo date("D d", $x);
    echo "</text>\n";
}

// Get all values to be plotted
$sql = "SELECT   s.sensor_name, i.sensor_desc, s.sensor_time, s.sensor_value
        FROM     xyz_sensors s
        JOIN     sensor_info i ON i.sensor_name = s.sensor_name
        WHERE    s.sensor_name like '$sensor%'
        AND      s.sensor_time > NOW() - INTERVAL $view DAY
        ORDER BY s.sensor_name, i.sensor_desc, s.sensor_time;";

if (!$result = $conn->query($sql)) {
    echo "Sorry, the website is experiencing problems.\n";
    exit;
}

// Draw data values
$current_sensor_name = "";
$current_sensor_colour = -1;
while ($reading = $result->fetch_assoc()) {
    $yv = round(500 - 500 * ($reading['sensor_value'] - $min_value) / ($max_value - $min_value), 0);
    $xv = round(1000 * (strtotime($reading['sensor_time']) - $min_time) / ($max_time - $min_time), 0);
    if ($reading['sensor_name'] != $current_sensor_name) {
        if ($current_sensor_name != "") echo "' />\n";
        $current_sensor_name = $reading['sensor_name'];
        $current_sensor_colour += 1;
        $colour = $colours[$current_sensor_colour];
        echo "<text fill=$colour x=$xv y=$yv >" . $reading['sensor_desc'] . "</text>\n";
        echo "<polyline fill=none stroke=$colour points='";
    }
    echo  "$xv $yv ";
}
echo "' />\n";

echo "</svg>";

$result->free();
$conn->close();

?>

</body>
</html>

Wow, looks complicated.

Thank you so much, this should help greatly with my project!

Sorry for bringing this thread back from the dead...

But was all of this code written in the arduino software? on one page?

Or was some of it written in a different coding software?

Also did you use an ethernet shield?

Hi, sorry, i have been going too fast. When you asked

mrears92:
Do i need to make the website using HTML/CSS then use PHP within the code to change the numerical values?

i assumed you understood more.

Only that first code i posted is Arduino code. It was written using the Arduino IDE.

The other 3 pieces of code are written in a language called PHP. I wrote them in a standard text exitor called gedit which comes with Ubuntu. You could use notepad in windows. There will be many choices of specialist editors for PHP and other languages out there for free, but i haven’t tried any yet.

PHP scripts run on web servers. You need to upload them to the web server, i use FireFTP to do this. FireFTP is free and can be downloaded as an add-on for the Firefox browser. But any FTP program would do the job. An FTP program just allows you to log onto the web server and upload files to it, so they can be viewed on the web.

No, i did not use an ethernet shield. I used an esp8266 module. These modules have wifi built in and their processors can be programmed using the Arduino IDE.

Here is a picture of the sensor i built recently. The module at top centre is the esp8266.

20160103_192818.jpg

Hope that help a little.

The below might be a display option.