ESP8266 วัดอุณหภูมิ ความชืนด้วย DHT11 เก็บข้อมูลลง Mysql และ thingspeak แจ้งเตือนผ่าน Line group พร้อมทั้งทำกราฟด้วย google chart






ภาพการต่อขาของ DHT11



ความสามารถ

1.นำข้อมูลอุณหภูมิและความชื้น เก็บไว้ใน database  Mysql

2.ส่งข้อมูลไปเก็บไว้ที่ IOT Cloud  Thingspeak

3.เมื่ออุณหภูมิสูงกว่า 35 องศาหรือตามที่ตั้งไว้ ก็จะแจ้งเตือนผ่าน Line group  โดยใช้ Line notify

4. สามารถแสดงผลเป็นกราฟได้ ( ดึงมาจาก thing speak )

5. สามารถแสดงผลเป็น Guage จาก Google chart

6.สามารถแสดงผลเป็นตารางจาก PHP  ได้


ภาพหน้าจอ php สำหรับดึงข้อมูลมาแสดงบนหน้าเว็บ โดยใช้ esp8266 ส่งข้อมูลลง mysql



 ภาพหน้าจอกราฟ ที่ดึงมาจาก thingspeak


                                                           ภาพกราฟ Gauge จาก google chart
สร้าง database สำหรับ Mysql ชื่อ Arduino
จากนั้นสร้าง table ชื่อ temp ซึ่งจะเก็บอุณหภูมิ และความชื้น

CREATE TABLE `temp` (
  `id` int(11) NOT NULL auto_increment,
  `temp` int(2) default NULL,
  `humidity` int(2) default NULL,
  `date` datetime default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;




//// code c++ ////





#include "DHT.h"
#include <ESP8266WiFi.h>
#include "ThingSpeak.h"
#include <ESP8266HTTPClient.h>


unsigned long myChannelNumber = channel;  /// thingspeak channel id จาก thingspeak
const char * myWriteAPIKey = "thing_speak_key";  // ได้มาจาก thingspeak

#define LINE_TOKEN "line_notify_token"
char tempF[6]; // buffer for temp incl. decimal point & possible minus sign


String message3;
String message4;
String message5;

#define DHTPIN D5     // wDhat digital pin we're connected to
#define DHTTYPE DHT11   // DHT 11
DHT dht(DHTPIN, DHTTYPE); // กำหนดให้ SENSOR อุณหภูมิความชื่น เข้าทาง D5

const char* ssid     = "ssid"; //Set Wifi SSID
const char* password = "wifi_password";//Set Wifi password
WiFiClient client;

void setup() {
  Serial.begin(115200);
  Serial.println("DHTxx test!");

   WiFi.begin(ssid, password);

  //Set WiFi mode
  //You can choose between WIFI_AP, WIFI_STA, WIFI_AP_STA or WIFI_OFF
  WiFi.mode(WIFI_STA);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  ThingSpeak.begin(client);

  dht.begin();
}

void Line_Notify(String message) {
 WiFiClientSecure client;

if (!client.connect("notify-api.line.me", 443)) {
 Serial.println("connection failed");
 return;
 }

String req = "";
 req += "POST /api/notify HTTP/1.1\r\n";
 req += "Host: notify-api.line.me\r\n";
 req += "Authorization: Bearer " + String(LINE_TOKEN) + "\r\n";
 req += "Cache-Control: no-cache\r\n";
 req += "User-Agent: ESP8266\r\n";
 req += "Content-Type: application/x-www-form-urlencoded\r\n";
 req += "Content-Length: " + String(String("message=" + message).length()) + "\r\n";
 req += "\r\n";
 req += "message=" + message;
 Serial.println(req);
 client.print(req);
 delay(2000);

Serial.println("-------------");
 while (client.connected()) {
 String line = client.readStringUntil('\n');
 if (line == "\r") {
 break;
 }
 Serial.println(line);
 }
 Serial.println("-------------");
}

void loop() {
  // Wait a few seconds between measurements.
  delay(8000);



  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed and exit early (to try again).
 // if (isnan(h) || isnan(t) || isnan(f)) {
   // Serial.println("Failed to read from DHT sensor!");
  //  return;
 // }

  // Compute heat index in Fahrenheit (the default)
  float hif = dht.computeHeatIndex(f, h);
  // Compute heat index in Celsius (isFahreheit = false)
  float hic = dht.computeHeatIndex(t, h, false);

  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.println();

   ThingSpeak.writeField(myChannelNumber, 1,t, myWriteAPIKey);
   ThingSpeak.writeField(myChannelNumber, 2,h, myWriteAPIKey);


 message3 = dtostrf(t, 6, 2, tempF);
 message5 = dtostrf(h, 6, 2, tempF);
if(t > 38){
   message4 = "Alert now temp so hot is "+ message3;
    Line_Notify(message4);
}else{
 //  Serial.print("Temperature: ");
 // Serial.print(t);
 // Serial.print(" *C ");

}
HTTPClient http;
http.begin("http://10.10.10.10/arduino/index.php");
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpCode = http.POST("temp="+ message3 +"&humidity=" + message5);
//Serial.println(httpCode);
if(httpCode == HTTP_CODE_OK)
{
 
 Serial.println("Insert to database success !!!");
}
else
{
   Serial.println("Error in HTTP request");
}

http.end();
}
 


///////////  php  สำหรับการ insert  data //////

สำหรับการเรียกใช้งาน  http://192.168.1.20/arduino/index.php?temp=32&humidity=30


<?php
 date_default_timezone_set('Asia/Bangkok');
$servername ="localhost";
$username = "root";
$password = " ";
$dbname = "arduino";
$now = new DateTime();

$temp = $_REQUEST['temp'];
$humidity = $_REQUEST['humidity'];

$conn = mysql_connect("localhost","root","");
if (!$conn)
{
    die('Could not connect: ' . mysql_error());
}
$con_result = mysql_select_db($dbname, $conn);
if(!$con_result)
{
die('Could not connect to specific database: ' . mysql_error());
}

$datenow = $now->format("Y-m-d H:i:s");
$hvalue = $value;

$sql ="insert  into  temp  (id,temp,humidity,date) values ( null,$temp,$humidity,'$datenow')";
// echo $sql;


$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
echo "<h1 align=center>THE DATA HAS BEEN SENT!!</h1>";
mysql_close($conn);
include ("show.php");
?>

///////////////////// for php 7 ///////////////////

<?php

 date_default_timezone_set('Asia/Bangkok');

$servername ="localhost";
$username = "root";
$password = "";
$dbname = "arduino";
$now = new DateTime();

$temp = $_REQUEST['temp'];
$humidity = $_REQUEST['humidity'];


$conn = mysqli_connect("localhost","root","");
if (!$conn)
{
    die('Could not connect: ' . mysqli_error());
}
//$con_result = mysqli_select_db($dbname);
$con_result = mysqli_select_db($conn, $dbname) or die(mysqli_error($con));
if(!$con_result)
{
 die('Could not connect to specific database: ' . mysqli_error());
}

 $datenow = $now->format("Y-m-d H:i:s");
 $hvalue = $value;

 $sql ="insert  into  temp  (id,temp,humidity,date) values ( null,$temp,$humidity,'$datenow')";
// echo $sql;


 $result = mysqli_query($conn, $sql);
 if (!$result) {
  die('Invalid query: ' . mysqli_error());
 }
 echo "<h1 align=center>THE DATA HAS BEEN SENT!!</h1>";
 mysqli_close($conn);

?>



/////////////////////////////////////////

//////  code php สำหรับการแสดงผล  show.php //



<html>
<head>
<title>kitti</title>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die("Error Connect to Database");
$objDB = mysql_select_db("arduino");
$strSQL = "SELECT * FROM temp";
$objQuery = mysql_query($strSQL) or die ("Error Query [".$strSQL."]");
?>
<table width="600" border="1" align="center">
  <tr>
    <th width="91"> <div align="center">ID </div></th>
    <th width="98"> <div align="center">TEMP </div></th>
<th width="98"> <div align="center">Humidity </div></th>
    <th width="198"> <div align="center">DATE </div></th>
 
  </tr>
<?php
while($objResult = mysql_fetch_array($objQuery))
{
?>
  <tr>
    <td><div align="center"><?php echo $objResult["id"];?></div></td>
    <td align="center"><?php echo $objResult["temp"];?></td>
<td align="center"><?php echo $objResult["humidity"];?></td>
    <td align="center"><?php echo $objResult["date"];?></td>
  </tr>
<?php
}
?>
</table>
<?php
mysql_close($objConnect);
?>
</body>
</html>


////////////////////////
//// code google chart ชนิด gauage ////



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<head>

  <title>Google Gauge - ThingSpeak</title>
<style type="text/css">
  body { background-color: #ffffff; }
</style>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js'></script> 
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>

var chart; 
var charts;
var data;

      google.load('visualization', '1', {packages:['gauge']});
      google.setOnLoadCallback(initChart);

function displayData(point) {
data.setValue(0, 0, 'Temp Dr');
data.setValue(0, 1, point);
chart.draw(data, options);
}

function loadData() {
// variable for the data point
var p;
               // ให้เปลี่ยนตัวเลข เป็น channel thingspeak เป็นของตัวเอง
$.getJSON('https://api.thingspeak.com/channels/229658/feed/last.json?callback=?', function(data) {
// get the data point
p = data.field1;
if (p)
{
//p = Math.round((p / 1023) * 100);
displayData(p);
}
});
}

function initChart() {

data = new google.visualization.DataTable();
data.addColumn('string', 'Label');
data.addColumn('number', 'Value');
data.addRows(1);
       
       chart = new google.visualization.Gauge(document.getElementById('chart_div'));
       options = {width: 320, height: 320, redFrom: 40, redTo: 100,
           yellowFrom:25, yellowTo: 40, minorTicks: 5};
loadData();

setInterval('loadData()', 1500);
       
}

</script>
  <body>
    <div id='chart_div' align="center"></div>
  </body>
</html>
</HTML>



//////

*** ถ้าหากมีปัญหาเรื่องภาษาไทยที่ส่งอ่านไม่ออก ให้เข้าเว็บไซด์นี้ http://meyerweb.com/eric/tools/dencoder/  ใส่ข้อความลงไปแล้ว copy เอามาใช้ครับ

ความคิดเห็น

  1. คำตอบ
    1. ขอสอบถามหน่อยคะ ยังไม่เข้าใจการนำโค้ดไปใช้อ่ะ

      ลบ
  2. Arduino Ethernet Shield สามารถแจ้งเตือนผ่านไลน์ได้ไหมครับ

    ตอบลบ
  3. ติดต่อผู้เขียน Blog ยังไงครับ

    ตอบลบ

แสดงความคิดเห็น

โพสต์ยอดนิยมจากบล็อกนี้

แจ้งเตือนเข้าไลน์กลุ่ม ผ่าน Line notify เมื่อมีคน login เข้า server ของเราผ่าน SSH (linux) หรือ remote desktop เข้ามา (windows server)

การทำ cloud iot ด้วย thingsboard ไว้ใช้เองครับ

การประยุกต์ใช้ line notify ในการแจ้งปัญหาการใช้งาน สำหรับ php