420 Magazine Background

Weatherstation 2.0

Teleon

Well-Known Member
Hey :welcome:

I started a grow and was tinkering around to get a good weatherstation with some data logging features - everything what u could buy is way to expensive, so I decided to make my own one ;)

It sends every 30s temperature, humidity and creates a UNIX timestamp while receiving.

blubber.jpg


What u need:
  • D1 Mini (ESP -12F, Model ESP8266MOD)
  • DHT 22 Temp / Humidity Sensor
  • Few wires
  • Standard grid hole PCB, two sided
  • And a bit of coding ;)
  • MySQL Database

IMAG1668.jpg

IMAG1670.jpg

IMAG1677.jpg

IMAG1675.jpg



The Code for the Arduino looks like that:

Code:
#include <ESP8266WiFi.h>
#include "DHT.h"

const char* ssid = "TEST"; //Your SSID
const char* password = "Test123"; //YOUR PW

int ledPin = D5;
int ledStatus = LOW;
WiFiServer server(80);

#define DHTPIN 0
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

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

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, ledStatus);

  Serial.print("Connecting to: ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.print("Successfully connected with:  ");
  Serial.print(ssid);

  dht.begin();

  server.begin();
  Serial.println("Server started");


  Serial.print("Adress : http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}

void loop() {

  WiFiClient client = server.available();

  client.flush();

  float tempValue = dht.readTemperature();
  float pressValue = dht.readHumidity();

if (isnan(tempValue) || isnan(pressValue)) {
     Serial.println("Unable to read DHT22");
}


delay(30000);
storeData(tempValue, pressValue);
delay(1); //1ms. Pause
}

void storeData(float tempValue,float pressValue){
    WiFiClient client;
    const char* host = "lalala.com";
    const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
      Serial.println("connection failed");
      return;
    }

    String url = "/TempHum.php?";
    url = url + "temp="+tempValue;
    url = url + "&press="+pressValue;

    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 "Connection: close\r\n\r\n");
    delay(1);
}
Then u need a Server with a Webserver running - there u need to add a *.php file where all the data gets "received" and which put it then into ur MySQL DB.

That could look like this:

PHP:
<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

  if (empty($_GET) || (!isset($_GET['temp']) || !isset($_GET['press']))) {
    echo "<h1>Es wurden keine oder nicht alle Parameter übergeben!</h1><br/>";
    echo "Mögliche Parameter sind:<br/>";
    echo "<ul>";
    echo "<li>temp - Temperatur</li>";
    echo "<li>press - Luftdruck</li>";
    echo "</ul><br/><br/>";
    $sampleLink = "http://progs.draeger-it.blog/wemosd1/dht11db/upload.php?temp=12.4&press=54.5";
    echo "zbsp.: <a href='$sampleLink'>$sampleLink</a>";
  } else {
    echo "<h2>Folgende Parameter wurden empfangen:</h2>";
    $tempValue = 0;
    $pressValue = 0;
    date_default_timezone_set('Europe/Berlin');
    $milliseconds = round(microtime(true));
    foreach ($_GET as $key => $value) {
      echo "Parameter: ";
      echo $key;
      echo "<br/>Wert:";
      echo $value;
      echo "<br/><br/>";
  
      if($key === 'temp'){
        $tempValue = $value;
      } else if($key === 'press'){
        $pressValue = $value;
      }
    }
    
    echo "Zeitstempel: ";
    echo date('d.m.Y H:i:s',$milliseconds);
    echo " (<i>automatisch</i>)";

    echo "<br/>";
    storeData($tempValue, $pressValue, $milliseconds);
  }

function storeData($tempValue, $pressValue, $milliseconds){
$stmt = "INSERT INTO `data` ";
$stmt .= "(`temp`, `press`, `timestamp`)";
$stmt .= " VALUES ('$tempValue', '$pressValue', $milliseconds)";

fireSQLStmt($stmt);

}

function fireSQLStmt($sqlStmt){
  $connection = getDBConnection();
  $result = mysqli_query($connection,$sqlStmt);
  return $connection->error;
}

function getDBConnection(){
  //Das bleibt Geheim!
  $dbname = "test";
  $dbusername = "root";
  $dbpassword = "blaa";
  $dburl='localhost';

  //Erzeugt einen Datenbanklink aus den Parametern (die Verbindungsdaten stehen in der Datei dbconfig.php)
    $link = mysqli_connect($dburl, $dbusername, $dbpassword,$dbname);
    if (!$link) {
        die('Verbindung schlug fehl: ' . mysqli_error());
    }

  /* check connection */
  if (mysqli_connect_errno()) {
       die($fehler1);
  }
  return $link;
}
?>
Sorry, some comments are german - but it should be clear ^^

Last step is to set a Webpage which show's all the nice data in a chart or in multiple charts ;)

PHP:
<?php
$connect = mysqli_connect("localhost", "root", "PW", "DB");
?>
<!DOCTYPE html>
<html>
      <head>
           <title>Temperature / Humidity Sensor</title>
           <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
           <script type="text/javascript">
      
           google.charts.load('current', {'packages':['corechart']});
           google.charts.setOnLoadCallback(drawTempChart);         
           function drawTempChart()
           {
                var data = google.visualization.arrayToDataTable([
                    ['Timestamp', 'Temperature'],
                    <?php
                    $query = "SELECT FROM_UNIXTIME(timestamp) AS zeit, temp FROM data";
                    $result = mysqli_query($connect, $query);
                    while($row = $result->fetch_assoc())
                    {
                        echo "['".$row["zeit"]."', ".$row["temp"]."],";
                    }
                    ?>
                ]);
                var options = {
                    title: 'Temperature in °C',
                    is3D:true,
                   hAxis: {
                      title: 'Time'
                   },
                   vAxis: {
                      title: 'Temperature'
                   },             
                   curveType: 'function',
                   backgroundColor: '#f1f8e9'
                    //pieHole: 0.4
                };
                var chart = new google.visualization.LineChart(document.getElementById('piechart'));
                chart.draw(data, options);
           }
      

           google.charts.load('current', {'packages':['corechart']});
           google.charts.setOnLoadCallback(drawHumChart); 
           function drawHumChart()
           {
                var data = google.visualization.arrayToDataTable([
                    ['Timestamp', 'Humidity'],
                    <?php
                    $query = "SELECT FROM_UNIXTIME(timestamp) AS zeit, press FROM data";
                    $result = mysqli_query($connect, $query);
                    while($row = $result->fetch_assoc())
                    {
                        echo "['".$row["zeit"]."', ".$row["press"]."],";
                    }
                    ?>
                ]);
                var options = {
                    title: 'Humidity in %',
                    explorer: {axis: 'horizontal'},               
                    is3D:true,
                                       hAxis: {
                      title: 'Time'
                   },
                   vAxis: {
                      title: 'Humidity'
                   },
                   curveType: 'function',
                   backgroundColor: '#f1f8e9'
                    //pieHole: 0.4
                };
                var chart = new google.visualization.LineChart(document.getElementById('piechart1'));
                chart.draw(data, options);
           }

           </script>
        </head>
          <link rel="stylesheet" href="styles.css">
          <body>
            <!--Table and divs that hold the pie charts-->
                <h3 align="center">Temperature / Humidity Sensor</h3>
                <br />
                <div id="piechart" style="width: 2000px; height: 400px;"></div>
                <br />
                <br />
                <div id="piechart1" style="width: 2000px; height: 400px;"></div>
          </body>
        </html>

Sooo and that's all - what u get is a nice neat monitor of ur temp and humidity :)

It's totally free, u can also add more sensors to monitor the top and the bottom ... or in my case I will also add another temp sensor to monitor the temp of my Selfmade LED Lamp!

Example : Click me


I hope somebody can do something with that! :Namaste:

-Teleon
 
Last edited:

CraZysWeeD

Well-Known Member
This is great Teleon!

I think there are more of us who wants to go do this but never get to it... you are an inspiration! :)

Some german I can handle. :)
 

odam2k

Well-Known Member
For the size, the ESP8266 is amazing... I run a webserver on it, and also MySQL Connector, so the only part I need to use my PC for is the MySQL Database itself.
 
Top Bottom