//安裝Adafruit Unified Sensor Library DHT Sensor Library #include #include #include #include #define DHTPIN 3 #define DHTTYPE DHT11 #define SSID "XXXAP" #define PASS "xxxxxxxx" #define SERVER "192.168.44.254" #define PORT "80" DHT_Unified dht(DHTPIN, DHTTYPE); SoftwareSerial ESP8266(11, 10); // RX, TX String cmd; String GET = "GET /aa.php?"; float T,H; void setup() { Serial.begin(115200); ESP8266.begin(115200); dht.begin(); delay(2000); sendDebug("AT+RST"); while (!ESP8266.find("OK")) delay(200); //delay(2000); Serial.println("Data ready to sent!"); connectWiFi(); } void loop() { sensors_event_t event; dht.temperature().getEvent(&event); T=event.temperature; Serial.print("T="); Serial.print(T); Serial.println(" *C"); dht.humidity().getEvent(&event); H=event.relative_humidity; Serial.print("H="); Serial.print(H); Serial.println("%"); delay(1000); ESP8266.println("AT+CIPMUX=1"); delay(1000); if (ESP8266.available()) Serial.write(ESP8266.read()); cmd="AT+CIPSTART=4,\"TCP\",\""; cmd +=SERVER; cmd +="\","; cmd +=PORT; ESP8266.println(cmd); delay(1000); if (ESP8266.available()) Serial.write(ESP8266.read()); cmd = GET + "tmp=" + T + "&hid=" + H +"\r\n"; Serial.print(cmd); ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4)); delay(1000); ESP8266.println(cmd); delay(1000); ESP8266.println(""); if (ESP8266.available()) Serial.write(ESP8266.read()); delay(10000); } void sendDebug(String wi) { Serial.print("SEND: "); Serial.println(wi); ESP8266.println(wi); } boolean connectWiFi() { ESP8266.println("AT+CWMODE=1"); delay(2000); String cmd="AT+CWJAP=\""; cmd+=SSID; cmd+="\",\""; cmd+=PASS; cmd+="\""; sendDebug(cmd); int cnt=0; while (!ESP8266.find("OK") && !ESP8266.find("No") && cnt<20 ) { delay(200); cnt++; } if (cnt<20) Serial.println( "Connect OK" ); else Serial.println( "Time Out" ); return true; }