ESP8266 Own CLoud

มาแล้วครับ  โค้ดสำหรับการเชื่่อม  Arduino ขึ้น  Cloud  MySQL แบบง่าย ๆ แต่มีคุณภาพ

 

#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <ESP8266HTTPClient.h>
#include "DHT.h"      
#include <WiFiUdp.h>
#include <Arduino.h>
#include <Wire.h>         // this #include still required because the RTClib depends on it
#include "RTClib.h"

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
#define Serial SerialUSB
#endif

RTC_Millis rtc;

// ----- แก้ค่า config 7 ค่าข้างล่างนี้ --------------------------------------------------------

const char* ssid = "AndroidAP-PS";
const char* password = "pwle0575";

//const char* ssid     = "true_home2G_F78";          // ชื่อ ssid
//const char* password = "96104427";      // รหัสผ่าน wifi

const char* host = "keepgreen.samongthailand.com";
//const char* timestamp = "datetime";

#define DHTPIN    D4          // GPIO2 ขาที่ต่อเข้ากับขา DATA (บางโมดูลใช้คำว่า OUT) ของ DHT
#define DHTTYPE   DHT11       // e.g. DHT11, DHT21, DHT22
DHT dht(DHTPIN, DHTTYPE);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
//int timestamp = "0";

String url;   // ใช้สำหรับ โปรแกรมส่วนการส่ง
  int count = 0;
//=====================
void setup() {
Serial.begin(115200); 
  
//=========== สำหรับการอ่านสถานะคำสั่ง led จาก server ======
  delay(100);
  pinMode(D5, OUTPUT);
  pinMode(D6, OUTPUT);
  pinMode(D7, OUTPUT);
  digitalWrite(D5, 0);
  digitalWrite(D6, 0);
  digitalWrite(D7, 0);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  
  WiFi.begin(ssid, password); 
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
 
  //Serial.println("");
  //Serial.println("WiFi connected");  
  //Serial.println("IP address: ");
  //Serial.println(WiFi.localIP());
  //Serial.print("Netmask: ");
  //Serial.println(WiFi.subnetMask());
  //Serial.print("Gateway: ");
  //Serial.println(WiFi.gatewayIP());
  //digitalWrite(D5, 1);
  //delay(10);
  digitalWrite(D5, 0);
  //delay(10);
  //digitalWrite(D6, 1);
  //delay(10);
  digitalWrite(D6, 0);
  //delay(10);
  //digitalWrite(D7, 1);
  //delay(10);
  digitalWrite(D7, 0);
  //delay(10);

//===== สิ้นสุด void setup สำหรับ การอ่านสถานะ led จาก server ======
//==== เริ่ม setup สำหรับ การส่งข้อมูลขึ้น server =====
rtc.begin(DateTime(F(__DATE__), F(__TIME__)));

//delay(100);
dht.begin();
//Serial.println();
//Serial.println();
//Serial.print("Connecting to ");
//Serial.println(ssid);
//WiFi.begin(ssid,password);

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

timeClient.begin();  // เตรียม เวลาสำหรับ time stamp

//Serial.println("");
//Serial.println("WiFi connected");
//Serial.println("IP address : ");
//Serial.println(WiFi.localIP());
//Serial.print("Netmask: ");
//Serial.println(WiFi.subnetMask());
//Serial.print("Gateway: ");
//Serial.println(WiFi.gatewayIP());

}

void loop() {
// getPCtime();
// === void loop for led status reading ===
Serial.print("connecting to ");
  Serial.println(host);
 
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }
 
  if (count == 0){
    url = "/api/led/read_all.php?id=1";
    count = count + 1;
    Serial.println("Here1");
  }
  else if (count == 1){
    url = "/api/led/read_all.php?id=2";
    count = count + 1;
    Serial.println("Here2");
  }
  else if (count == 2){
    url = "/api/led/read_all.php?id=3";
    count = count + 1;
    Serial.println("Here3");
  }
  Serial.print("Requesting URL: ");
  Serial.println(url);
  
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: close\r\n\r\n");
  delay(200);
  String section="header";
  while(client.available()){
    String line = client.readStringUntil('\r');
    //Serial.print(line);
    // we’ll parse the HTML body here
    if (section=="header") { // headers..
     
      if (line=="\n") { // skips the empty space at the beginning 
        section="json";
      }
    }
    else if (section=="json") {  // print the good stuff
      section="ignore";
      String result = line.substring(1);
 
      // Parse JSON
      int size = result.length() + 1;
      char json[size];
      result.toCharArray(json, size);
      StaticJsonBuffer<700> jsonBuffer;
      JsonObject& json_parsed = jsonBuffer.parseObject(json);
      if (!json_parsed.success())
      {
        Serial.println("parseObject() failed");
        return;
      }
      //String led = json_parsed["led"][0]["status"];
      String led1 = json_parsed["led"][0]["status"];
      String led2 = json_parsed["led"][1]["status"];
      String led3 = json_parsed["led"][2]["status"];
      // string led = json_parsed["table name""][array number]["value of filed"]
      
      //if(count == 1){
        if(led1 == "on"){
          digitalWrite(D5, 1);
          delay(10);
          Serial.println("D5 is On..!");
        }
        else if(led1 == "off"){
          digitalWrite(D5, 0);
          delay(10);
          Serial.println("D5 is Off..!");
        }
      //}
      //else if(count == 2){
        if(led2 == "on"){
          digitalWrite(D6, 1);
          delay(10);
          Serial.println("D6 is On..!");
        }
        else if(led2 == "off"){
          digitalWrite(D6, 0);
          delay(10);
          Serial.println("D6 is Off..!");
        }
      //}
      //else if(count == 3){
        if(led3 == "on"){
          digitalWrite(D7, 1);
          delay(10);
          Serial.println("D7 is On..!");
        }
        else if(led3 == "off"){
          digitalWrite(D7, 0);
          delay(10);
          Serial.println("D7 is Off..!");
        }
        count = 0;
      //}
 
      if (count == 3)
        count = 0;
       
    }
  }
  Serial.println();
  Serial.println("closing connection");
  //delay(10);

// == end of void for led status ===

 timeClient.update();
 String timestamp = timeClient.getFormattedTime();
 float h = dht.readHumidity();
 float t = dht.readTemperature();
 if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor");
    return;
 }
Serial.print("connecting to ");
Serial.println(host);

//WiFiClient client;
//const int httpPort = 80;
if (!client.connect(host, httpPort)) {
  Serial.println("connection failed");
  return;
}

String url = "/api/weather/insert.php?temperature=" + String(t) + "&humidity=" + String(h) + "&pressure=" + String(h) +"&time_stamp=" + String(timestamp);
Serial.print("Resquesting URL: ");
Serial.println(url);

client.print(String("GET ") + url + " HTTP/1.1\r\n" + 
            "Host: " + host + "\r\n" +
            "Connection: close\r\n\r\n");
delay(100);

while(client.available()){
   String line = client.readStringUntil('\r');
   Serial.print(line);
}

Serial.println();
Serial.println("closing connection");
delay(10);
}

 

420 total views, 2 views today

ใส่ความเห็น