2.無線氣象站

http://192.168.1.91:8080

#include <SoftwareSerial.h>

#include <DHT.h>                      //載入DHT.h函式庫

#define DHTPIN 8                     //將DHT11連接到8腳位    

#define DHTTYPE DHT11           //設定感測器型號為DHT11

DHT dht(DHTPIN, DHTTYPE);

#define TX 3   //ESP8266 TX接3

#define RX 2  //ESP8266 RX接2

#define SSID " "    //這裡填入你家AP的SSID

#define PASSWORD " "   //這裡填入你家AP的密碼

SoftwareSerial esp8266(TX,RX); 

#define DEBUG true

void setup() {

  Serial.begin(9600); //start hardware serial port

  esp8266.begin(9600); //start soft serial port

  pinMode(13,OUTPUT);  //連線指示燈

  String cmd="AT+CWJAP=\"";

  cmd+=SSID;

  cmd+="\",\"";

  cmd+=PASSWORD;

  cmd+="\"";

  cmd+="\r\n";

  sendData("AT+RST\r\n",2000,DEBUG); //重啟ESP8266

  sendData("AT+CWMODE=1\r\n",100,DEBUG); // 設定為STA模式

  sendData(cmd,10000,DEBUG); // 取得連線(視AP連線效能作調整,預設7000毫秒)

  sendData("AT+CIFSR\r\n",100,DEBUG); // 獲得IP

  sendData("AT+CIPMUX=1\r\n",100,DEBUG); // 開啟多除連接模式

  sendData("AT+CIPSERVER=1,8080\r\n",100,DEBUG); // 設定連接埠為8080

 

  }

void loop() {

digitalWrite(13,1);  //當ESP8266 連上AP,自動亮燈

int h = dht.readHumidity();       //讀取感測器濕度

int  t = dht.readTemperature();  //讀取感測器溫度

   

  if (esp8266.available()) { 

    if (esp8266.find("+IPD,")) {  //收到客戶端的連線要求, 進行回應

      delay(1000);

      // +IPD, 後的字元是連線 ID (ASCII碼), 用 read() 讀取後減 48 為數字

      int connectionId = esp8266.read()-48; 

 

      String webpage="Temperature=";

      webpage += t;

      webpage +="  Humidity=";

      webpage += h;

      String cipSend = "AT+CIPSEND=";

      cipSend += connectionId;

      cipSend += ",";

      cipSend +=webpage.length();

      cipSend +="\r\n";

      sendData(cipSend,100,DEBUG);

      sendData(webpage,10000,DEBUG); //延遲時間800毫秒可以自行調整

     

      String closeCommand = "AT+CIPCLOSE=";

      closeCommand+=connectionId; // append connection id

      closeCommand+="\r\n";   

      sendData(closeCommand,100,DEBUG);

      }

    }

  }

String sendData(String command, const int timeout, boolean debug) {

  String response="";

  esp8266.print(command); // send the read character to the esp8266

  long int time=millis();

   do{

    while(esp8266.available()) {

      // The esp has data so display its output to the serial window

      char c=esp8266.read(); // read the next character.

      response += c;

      } 

      if(response.charAt(response.length()-2)=='O'&&response.charAt(response.length()-1)=='K'){

        time=0;

      }

    }while ((time+timeout) > millis());

  if (debug) {Serial.print(response);}

  return response;

  }