Logging Data to Web Page using Arduino and ESP8266-01 (AT)


Description:  This document will walk us through the procedure of logging sensor data such as temperature, humidity, and water level to a MySQL Database on a VPS server.  This data will then be displayed on a web page.

Prerequisites:   If you do not have a server already set up, you can use this page to set up a VPS server.

http://bryceautomation.com/index.php/configuring-virtual-private-server/

Please follow the following link to set up the database on your server for this project.    This database will be used to log data that can be displayed on your web page.

Configuring a Database to log data for Arduino Projects

We will just need a database and user set up with permissions.

Also, we will assume that you have some basic knowledge of how to set up an Arduino project.

Disclaimer:  You are fully responsible for all safety and security.  This information is provided “as-is” without any guarantee of any kind.    If you find errors on this document, however, please let me know.   I would like this information to be as accurate as possible.

Step 1 — Gather your components.

This project will require an Arduino UnArduino Componentso (but you can use almost any arduino that has a TX and RX on it), a Logic Level Converter (to convert the 5v TX and RX to 3.3v.  An ESP8266-01 (With AT firmware loaded), a DHT-22 (Temperature and Humidity Sensor), and some kind of analog level sensor (represented here by a simple potentiometer).   You will also need a 3.3v DC Power supply for the ESP8266-01, and for the Logic Level Converter.  We will just plug the Arduino into our USB port for power. (Image created with Fritzing)

 

Step 2 — Make your connections to Arduino and ESP8266-01

The DHT-22 will connect to Digital Pin 2, and the Analog level sensor’s signal will connect to Analog 0.    TX and RX will go through the logic level converter, and TX on the Arduino will go to the RX on the ESP8266-01, and vice versa.

You will need to supply 3.3v to the ESP8266-01 on it’s power pins, and the low voltage pins of the logic level converter.

You can use the Arduino’s 5v to supply the sensors, and the high voltage pins of the logic level converter.

Be sure to connect the ground of the 3.3v supply to the ground of the arduino.   Do not use the 3.3v output of the arduino to power the ESP8266.  You will need a separate source of power this.

Basement ProjectHere is an image of my final project.   I’ve simulated the Uno using the Atmega 328 on a prototype board, and the ESP8266-01 is on a sepa
rate prototype board for ease of programming, making changes, and troubleshooting in the future.

 

Step 3 — The sketch

The arduino sketch will configure the SSID and password on the ESP8266-01 through the use of AT commands.  This sketch will also gather data from the sensors and pass that data to the server.   Since we are declaring the number of characters, and logging the data as Integer, I’m multiplying any floating point signal by 100, and adding 10000.   The purpose of adding 10000 is to hold the number of characters constant while the data is transmitted, and this value will be subtracted once it gets to the server.  Decimal data (x100) that gets logged to the database will later be divided by 100 before it is displayed to the user.  There are other methods that you can choose to use to make this process a little more clean, but I’m using this method to keep the code itself fairly simple.  Be sure to change your SSID, password, server IP address, etc before downloading.   This is an example only, but if you have the database configured according to the link above, and make the necessary changes, everything should work fine.  Also, be sure to set the baud rate according to the baud rate of your ESP8266-01 for serial.  This example uses 115200, but some firmware uses 9600.    This example is just modified from the DHT library example, and Analog Read Serial.  While downloading, you might want to temporarily remove the TX and RX lines from the ESP8266-01 to avoid interference.

Note:  You will need to have the DHT library installed on your pc.  At the time of this writing, the DHT22 Library can be found at:  

https://github.com/adafruit/DHT-sensor-library

Just extract the zip file, copy it into your arduino libary folder, and be sure all windows are closed in the Arduino IDE.  Now, restart the arduino IDE and use this code:


/*
AnalogReadSerial
Reads an analog input on pin 0, prints the result to the serial monitor.
Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

This example code is in the public domain.
*/
#include "DHT.h"

#define DHTPIN 2 // what digital pin we're connected to

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
DHT dht(DHTPIN, DHTTYPE);
// the setup routine runs once when you press reset:
void setup() {
pinMode(13, OUTPUT);
delay(3000);
dht.begin();
// initialize serial communication at 9600 bits per second:
Serial.begin(115200);
Serial.println("AT+CWMODE=1");
delay(1000);
Serial.println("AT+CWJAP=\"RouterSSID\",\"RouterPassword\"");
delay(1000);

}

// the loop routine runs over and over again forever:
void loop() {
digitalWrite(13, LOW);
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = (dht.readHumidity()*100+10000);
// Read temperature as Celsius (the default)
float t = (dht.readTemperature()*100+10000);
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = (dht.readTemperature(true)*100+10000);
int fahrenheit=f;
int celsius=t;
int humidity=h;

// read the input on analog pin 0:
int sensorValue = analogRead(A0);
int adjustedValue = sensorValue+10000;
// print out the value you read:
Serial.println("AT+CIPSTART=\"TCP\",\"192.168.1.10\",80");
delay(1000);
Serial.println("AT+CIPSEND=66");
delay(1000);
Serial.print("GET /basementlog.php?level=");
Serial.print(adjustedValue);
Serial.print("&fahrenheit=");
Serial.print(fahrenheit);
Serial.print("&humidity=");
Serial.println(humidity);
delay(1000);
Serial.println("AT+CIPCLOSE");
digitalWrite(13, HIGH);
delay(100000); // delay in between reads for stability
}

Step 4 — Your Server’s PHP file for logging the data.

I’ve placed the following code in the server’s public_html directory as a file named basementlog.php   This code will receive data from the arduino when it requests this page, condition the data, and log the data into the database.  Be sure to adjust the database, user, and password as needed.


<?php

$fahrenheit=($_REQUEST["fahrenheit"]);
$humidity=($_REQUEST["humidity"]);
$level = trim($_REQUEST["level"]);
$level=$level-10000;
$fahrenheit=$fahrenheit-10000;
$humidity=$humidity-10000;
//$level=$level*2/1000;
//$level= number_format($level,3);
//print ($level);

$servername = "localhost";
$username = "arduino";
$password = "password";
$dbname = "arduino";
if ($level){
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO basementlevel (id, level, fahrenheit, humidity, timestamp) VALUES ('', '$level', '$fahrenheit', '$humidity', now())";

 

if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}

$conn->close();
// $level=600;  // test

// To send out an email, you must have POSTFIX or another sendmail type daemon installed.

if ($level > 60){
$to = 'ricky@irvingil.us';
//$to = 'yourphone#@txt.att.net'; // Enter an email that you will text  your phone if you want to use this instead of email
$subject = 'Basement Level';
$message = 'Basement Level is ' . $level;
$headers = 'From: apache@irvingil.com' . "\r\n" .
'Reply-To: youremail@youremail.com . "\r\n" .
'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
}
}

?>

 

 

Step 5 — Display data for the user to read

Next, we will add a page that can be accessed directly by a web browser.   We will place this code again in the public_html directory.  The script can be accessed by a web browser by going to http://mysite/basementlevel.php   You will need to modify the database information as needed.


<?php
$page = $_SERVER['PHP_SELF'];
$sec = "120";
header("Refresh: $sec; url=$page");
$servername = "localhost";
$username = "arduino";
$password = "mypassword";
$dbname = "arduino";
print ("<h2>Basement Water Level, Temperature, and Humidity</h2>");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT id, level, fahrenheit, humidity, timestamp FROM basementlevel order by timestamp desc limit 72";
$result = $conn->query($sql);

print ("<table cellpadding=5 cellspacing=5 border=3><tr><td><b>ID</b></td><td><b>Level</b></td><td><b>Fahrenheit</b></td><td><b>Humidity</b></td><td><b>Timestamp</b></td></tr>");
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$level=$row["level"]*2/1000;
$fahrenheit=$row["fahrenheit"]/100;
$humidity=$row["humidity"]/100;

if ($count==0){
echo "<tr><td>" . $row["id"] . "</td><td>" . $level . " inches</td>"
."<td>" . $fahrenheit . "</td>"
."<td>" . $humidity . "</td>"
. "<td>". $row["timestamp"] . " UTC</td></tr>";
}
$count++;
if ($count==6){
$count=0;
}

}
print ("</table>\n");

} else {
echo "0 results";
}
$conn->close();
print ("<h3><i>-- Ricky Bryce</i></h3>");
?>

That’s it!   Be sure your project is connected, and powered up….   You should be logging data.   If you need to troubleshoot your project, you can manually enter the basementlog.php in your web browser, and pass variables onto the server in the URL.   To troubleshoot your project, you can disconnect the ESP8266-01, and be sure the correct AT commands are being passed using your Serial Monitor in the Arduino IDE.

ESP Web Page

— Ricky Bryce

Leave a comment

Your email address will not be published. Required fields are marked *

8 + = 14