Asas IOT – memuat naik data dari Arduino ke PHP/MySQL (Bahagian 1)

Ini adalah sambungan kepada projek sebelum ini di mana kita melihat bagaimana untuk memaparkan data dari sensor C02, Suhu, Kelembapan dan PM2.5.

Kita memperkenalkan konsep IOT dengan menambah satu lagi komponen iaitu Cytron Grove ESP8266 wifi untuk membolehkan data dari arduino dimuatnaik di internet.

anda boleh melihat bacaan sensor terkini di sini

Saya juga memasang Apache-MySQL-PHP di dalam pelayan berasaskan Ubuntu dan menyediakan 4 skrip iaitu:

  • Arduino – untuk membaca bacaan sensor dan menghantar ke internet
  • environment.php – untuk memasukkan data ke pengkalan data MySQL
  • service.php – untuk mengeluarkan data dari pengkalan data MySQL
  • index.php – untuk memaparkan di atas carta

#include <CytronWiFiShield.h> #include <CytronWiFiClient.h> #include "SCD30.h" #include <pm25.h> #include <CytronWiFiServer.h> #include <SoftwareSerial.h> #include "EasyNextionLibrary.h" const char *ssid = "SSID wifi anda"; const char *pass = "password wifi anda"; IPAddress destserver(192,168, x , x); //alamat pelayan Apache/PHP/MySQL #define SERIAL Serial EasyNex myNex(SERIAL); SoftwareSerial pm25_ser(4,5); void PM25_listen(){ if(!pm25_ser.isListening()){ pm25_ser.listen(); } } void setup() { scd30.initialize(); // put your setup code here, to run once: Serial.begin(9600); myNex.begin(9600); pm25_ser.begin(9600); PM25.init(&pm25_ser, &Serial, PM25_listen); if(!wifi.begin(2, 3)) { Serial.println(F("Error talking to shield")); while(1); } Serial.println(wifi.firmwareVersion()); Serial.print(F("Mode: "));Serial.println(wifi.getMode());// 1- station mode, 2- softap mode, 3- both Serial.println(F("Start wifi connection")); if(!wifi.connectAP(ssid, pass)) { Serial.println(F("Error connecting to WiFi")); while(1); } Serial.print(F("Connected to ")); Serial.println(wifi.SSID()); Serial.println(F("IP address: ")); Serial.println(wifi.localIP()); wifi.updateStatus(); Serial.println(wifi.status()); //2- wifi connected with ip, 3- got connection with servers or clients, 4- disconnect with clients or servers, 5- no wifi } void loop() { float result[3] = {0}; float particle = PM25.read(); if (scd30.isAvailable()) { scd30.getCarbonDioxideConcentration(result); myNex.writeStr("tCO2.txt", String(result[0])); myNex.writeStr("tHumidity.txt", String(result[2])); myNex.writeStr("tTemp.txt", String(result[1])); myNex.writeStr("tPm.txt",String(particle)); const char* host = "192.168.x.x"; //alamat hos Apache-MySQL-PHP ESP8266Client client; if (!client.connect(host, 80)) { Serial.println(F("Failed to connect to server.")); client.stop(); return; } String httpRequest = "GET /environment.php?CO2="+String(result[0])+"&Humidity="+String(result[1])+"" "&Temperature="+String(result[2])+"&PM25="+String(particle)+" " "HTTP/1.1\r\n" "Host: 192.168.x.x\r\n" "Connection: close\r\n\r\n"; //Serial.println (httpRequest); if(!client.print(httpRequest)) { Serial.println(F("Sending failed")); client.stop(); return;; } delay(15000); } }
Code language: PHP (php)
<?php class environment{ public $link=''; function __construct($CO2,$Temperature,$Humidity,$PM25){ $this->connect(); $this->storeInDB($CO2, $Temperature,$Humidity,$PM25); } function connect(){ $this->link = mysqli_connect('localhost','yourusername','yourpassword') or die ('cannot connect to the DB'); mysqli_select_db($this->link,'environment') or die ('cannot select the DB'); } function storeInDB($CO2, $Temperature, $Humidity, $PM25){ $query ="insert into environment set CO2='".$CO2."', Temperature='".$Temperature."', Humidity='".$Humidity."', PM25='".$PM25."'"; $result = mysqli_query($this->link,$query) or die ('Errant Query '.$query); } } if($_GET['CO2'] != '' and $_GET['Temperature'] != '' and $_GET['Humidity'] != '' and $_GET['PM25'] != ''){ $environment=new environment($_GET['CO2'],$_GET['Temperature'], $_GET['Humidity'], $_GET['PM25']); } ?>
Code language: HTML, XML (xml)
<?php $username = "yourusername"; $password = "yourpassword"; $dbname = "environment"; // Create connection $conn = new mysqli('',$username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM (SELECT ID, DateTime, CO2,Temperature, Humidity,PM25 FROM environment ORDER BY ID DESC LIMIT 30) t1 ORDER BY t1.ID"; $result = $conn->query($sql); if ($result->num_rows > 0) { // output data of each row $obj = array(); while($row = $result->fetch_assoc()) { $element = array($row["DateTime"],$row["CO2"],$row["Temperature"],$row["Humidity"],$row["PM25"]); array_push($obj,$element); } echo json_encode($obj); } else { echo "0 results"; } $conn->close(); ?>
Code language: HTML, XML (xml)
<head> <script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script> <script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script> <script type="text/javascript"> window.onload = function () { var chart = new CanvasJS.Chart("chartContainer",{ title:{ text:"Sidik.My Environment Chart" },axisX: { title: "Time", suffix : "" }, axisY: { title: "CO2", titleFontColor: "#4F81BC", suffix : " PPM", lineColor: "#4F81BC", tickColor: "#4F81BC" }, axisY2: { title: "T,H & PM25 ", titleFontColor: "#C0504E", suffix : " °C ,% & ug/m ", lineColor: "#C0504E", tickColor: "#C0504E" }, data: [{ type: "column", name : "CO2 (PPM)", axisYType: "primary", dataPoints : [], }, { type: "line", axisYType: "secondary", dataPoints : [], }, { type: "line", axisYType: "secondary", dataPoints : [], }, { type: "area", axisYType: "secondary", dataPoints : [], }] }); $.getJSON("service.php", function(data) { $.each((data), function(key, value){ chart.options.data[0].dataPoints.push({label: value[0], y:parseInt(value[1])}); chart.options.data[1].dataPoints.push({label: value[0], y:parseInt(value[2])}); chart.options.data[2].dataPoints.push({label: value[0], y:parseInt(value[3])}); chart.options.data[3].dataPoints.push({label: value[0], y:parseInt(value[4])}); }); chart.render(); updateChart(); }); function updateChart() { $.getJSON("service.php", function(data) { chart.options.data[0].dataPoints = []; chart.options.data[1].dataPoints = []; chart.options.data[2].dataPoints = []; chart.options.data[3].dataPoints = []; $.each((data), function(key, value){ chart.options.data[0].dataPoints.push({label: value[0], y: parseInt(value[1])}); chart.options.data[1].dataPoints.push({label: value[0], y: parseInt(value[2])}); chart.options.data[2].dataPoints.push({label: value[0], y: parseInt(value[3])}); chart.options.data[3].dataPoints.push({label: value[0], y:parseInt(value[4])}); }); chart.render(); }); } setInterval(function(){updateChart()}, 1000); } </script> </head> <body> <div id="chartContainer" style="height: 500px; width: 90%;"></div><br> </body> </html>
Code language: HTML, XML (xml)

Leave a Reply

Alamat e-mel anda tidak akan disiarkan.

Related Post