---
title: "Temperature and humidity sensor on arduino with sending and drawing a graph"
url: "https://maker.wiznet.io/WIZnet/projects/temperature-and-humidity-sensor-on-arduino-with-sending-and-drawing-a-graph/"
markdown_url: "https://maker.wiznet.io/WIZnet/projects/temperature-and-humidity-sensor-on-arduino-with-sending-and-drawing-a-graph/md"
type: "UCC: User Created Content"
author: "LosChikatilos"
author_url: "https://habr.com/ru/post/460491/"
editor: "WIZnet"
editor_url: "https://maker.wiznet.io/"
original_author: "LosChikatilos"
original_url: "https://habr.com/ru/post/460491/"
published: "2023-02-03"
language: "en"
likes: 1
views: 568
comments: 0
source: "WIZnet Makers (https://maker.wiznet.io/)"
---

# Temperature and humidity sensor on arduino with sending and drawing a graph

> The main task of the project is to monitor the temperature in the greenhouse 11-15 meters away from the house. Without the possibility of or

Original author: LosChikatilos (source: https://habr.com/ru/post/460491/)

## Article

**DETAILS**

The main task of the project is to monitor the temperature in the greenhouse 11-15 meters away from the house. Without the possibility of organizing the UTP strip and power supply before it.

Greenhouse part:

1. Take temperature / humidity with DHT-11 sensor using pro micro

2. Send fs1000a with pro micro

Home part:

1. Accept values ​​on mx-rm-5v using Uno

2. Send to server using Ethernet shield (WIZNET W5100)

3. Write to mysql database

4. Draw a graph (jpgraph)

![](https://habrastorage.org/r/w1560/webt/r-/vx/8f/r-vx8f0ac10qn0zgf2cynaayoj8.jpeg)

I started out a little out of order. For me, this sequence turned out to be more complicated, so I decided to implement it first.

The list of required packages is not huge and depends on the distribution, namely nginx, php-gd, php-mysql, mysql-server. Jpgraph may need ttf fonts.

Prepare nginx

```plaintext
server {
listen 80;
listen [::]:80;
root /var/www/html;
 location / {
               }
location ~ .php$ {
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    # With php7.0-cgi alone:
    # fastcgi_pass 127.0.0.1:9000;
    # With php7.0-fpm:
    fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 256 32k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_connect_timeout 1s;
    fastcgi_ignore_client_abort off;
    fastcgi_next_upstream timeout;
    fastcgi_read_timeout 5m;
    fastcgi_send_timeout 5m;
    }
}
```

For uno we need the following libraries:
SPI.h
Ethernet.h
DHT.h

Code for UNO

```plaintext
#include <SPI.h>
#include <Ethernet.h>
#include <DHT.h>

// MAC address for controller
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
//Адрес шилда
byte ip[] = { 192, 168, 156, 192 };
//Маска
byte subnet[] = { 255, 255, 255, 0 };
//Шлюз
byte gateway[] = { 192, 168, 0, 1 };
//Адрес сервера с базой
char server[] = "192.168.156.186";
#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE); 

//Запуск клиента
EthernetClient client;

void setup() 
{
 dht.begin();
   
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect
    }
   
{        Ethernet.begin(mac,ip,gateway,subnet);
    }

    // give the Ethernet shield a second to initialize
    delay(1000);
   }

void loop()
{
  if (client.connect(server, 80))
  {
  // give the Ethernet shield a second to initialize
  float h = dht.readHumidity();
  float t = dht.readTemperature();
         Serial.println("connected");
        // Отправляем GET запрос с данными
        client.println(String("GET /index.php?temp=")+ t +"&hum="+h);
           client.println();
        Serial.println("connection close");
      } else Serial.println("connection failed");
      delay(60000);
}
```

The sketch sends a GET request to the script (index.php) every minute:

index.php

```plaintext
<?php
/**
 * @param string            $message
 * @param PDOException|null $exception
 */
function writeMessage($message, $exception = null)
{
    $logfile = '/var/www/html/data/arduino.log';
    $datetime = date('d.m.Y H:i:s', time());

    if ($exception !== null) {
        $message .= ': ' . $exception->getFile() . ' (line: ' . $exception->getLine() . ') - ' . $exception->getMessage();
    }

    file_put_contents($logfile, '[' . $datetime . '] ' . $message."n", FILE_APPEND);
}

/* Подключение к базе данных MySQL с помощью вызова драйвера */
$dsn = 'mysql:dbname=greenhouse;host=localhost';
$user = 'arduino';
$password = 'парол';

try {
    $dbh = new PDO($dsn, $user, $password, [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
    ]);
} catch (PDOException $e) {
    writeMessage('Произошла ошибка', $e);
}

try {
    $sth = $dbh->prepare('INSERT INTO data (sensor, temperature, humidity, created_at) VALUES (?, ?, ?, NOW())');
    $sth->execute(['grass', $_REQUEST['temp'], $_REQUEST['hum']]);

} catch (PDOException $e) {
    writeMessage('Произошла ошибка', $e);
}
```

which in turn sends the values ​​to the base:

Creating a table

```plaintext
CREATE DATABASE `greenhouse` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
```

```plaintext
CREATE TABLE `table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `sensor` varchar(255) DEFAULT NULL,
  `temperature` decimal(6,3) DEFAULT '0.00',
  `humidity` decimal(6,3) DEFAULT '0.00',
  `created_at` datetime DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;
```

Add a user and issue permissions

```plaintext
CREATE USER 'arduino'@''' IDENTIFIED BY 'парол';
```

```plaintext
GRANT ALL PRIVILEGES ON * . * TO 'arduino'@'';
```

```plaintext
FLUSH PRIVILEGES;
```

We check:

```plaintext
select * from data;
```

```plaintext
+-----+--------+-------------+----------+---------------------+
| id  | sensor | temperature | humidity | created_at          |
+-----+--------+-------------+----------+---------------------+
|   1 | grass  |        NULL |     NULL | 2019-07-15 13:29:13 |
|   2 | grass  |      24.100 |   49.000 | 2019-07-15 13:44:44 |
|   3 | grass  |      24.100 |   49.000 | 2019-07-15 13:44:54 |
|   4 | grass  |      24.000 |   49.000 | 2019-07-15 13:45:04 |
|   5 | grass  |      24.000 |   49.000 | 2019-07-15 13:45:15 |
|   6 | grass  |      24.100 |   49.000 | 2019-07-15 13:45:25 |
|   7 | grass  |      24.100 |   49.000 | 2019-07-15 13:45:35 |
|   8 | grass  |      24.100 |   49.000 | 2019-07-15 13:45:45 |
|   9 | grass  |      24.100 |   49.000 | 2019-07-15 13:45:55 |
|  10 | grass  |      24.100 |   48.000 | 2019-07-15 13:46:47 |
|  11 | grass  |      24.100 |   48.000 | 2019-07-15 13:46:58 |
|  12 | grass  |      24.100 |   48.000 | 2019-07-15 13:47:08 |
```

Data in the database!

Install the [JpGraph](https://jpgraph.net/download/) library [,](https://jpgraph.net/download/)

remove it to / var / www / src

Now draw the graph (day.php):

day.php

```plaintext

```

We get this kind of beauty:

---

Source: https://maker.wiznet.io/WIZnet/projects/temperature-and-humidity-sensor-on-arduino-with-sending-and-drawing-a-graph/
