ESP8266/WemosD1開發板聯網教程 Arduino程序,相關物聯網功能直接往標注的地方加內容就行了,拿來配置好環境即能用,保姆級注釋
一 、實現功能:通過開發板檢測mq3傳感器數據,連接周圍Wifi,向云服務器發送數據/請求數據。
二 、設備工具:
1、ESP8266/WemosD1開發板 (Arduino其他開發板連接esp8266模塊也可以)
2、服務器接口
電路原理圖如下:
51hei.png (142.95 KB, 下載次數: 62)
下載附件
2022-4-1 02:09 上傳
三、代碼:
- #include <Arduino.h>
- #include <ESP8266HTTPClient.h>
- #include <ESP8266WiFi.h>
- #include <ESP8266WiFiMulti.h>
- #define USE_SERIAL Serial
- //wifi實例化
- // 成功返回 接收數據
- ESP8266WiFiMulti WiFiMulti;
- //////////////////////// D1 連接wifi
- //wifi
- char ssid[] = "test"; // 路由器wifi名稱(盡量不要用中文)
- char paswd[] = "123456789"; // 路由器wifi密碼
- String myserver = "http://xxxxx:80/addtest"; //可以是網址可以是 ip地址,如果訪問失敗請注意接口網址最后是否需要加一個 /
- void setup() {
- /* wifi 初始化*/
- USE_SERIAL.begin(115200);
- USE_SERIAL.setDebugOutput(false);
- USE_SERIAL.println();
- USE_SERIAL.println();
- USE_SERIAL.println();
- for (uint8_t t = 4; t > 0; t--) {
- USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
- USE_SERIAL.flush();
- delay(1000);
- }
- WiFi.mode(WIFI_STA);
- WiFiMulti.addAP(ssid, paswd);
- /* mq3 傳感器*/
- pinMode(A0,INPUT);
- // 注意:arduinoUno等板子 使用 1 2 3(數字接口) A0 A1(模擬接口)
- // Esp8266/Wemos 使用 D1 D2 D3(數字接口) A0 (模擬接口只有A0)
- }
- void loop() {
- // 讀取A0引腳數據
- int mq3Date = analogRead(A0);
- //此處可以寫其他功能代碼,比如顯示屏、傳感器檢測、報警模塊等,本例使用MQ3傳感器作為數據來源
- // web
- String urlDate = "?mq=" + String(mq3Date);
- wifimodel(urlDate);
- }
- //封裝Web功能
- void wifimodel(String urlDate){
- // 等待wifi連接
- if ((WiFiMulti.run() == WL_CONNECTED)) {
- WiFiClient client;
- HTTPClient http;
- USE_SERIAL.print("[HTTP] begin...\n");
- // 大量數據拼接示例:String urls = myserver + "?o2data1=" + String(o2data1) + "&o2data2=" + String(o2data2);
- // Get方式請求接口,接口url拼接示例: www.baidu.com/my?o2data1=123&o2data2=2323
- String urls = myserver+urlDate;
- Serial.println("拼接url為:" + urls);
- http.begin(client, urls); //HTTP
- USE_SERIAL.print("[HTTP] GET...\n");
- // start connection and send HTTP header
- int httpCode = http.GET();
- // httpCode will be negative on error
- if (httpCode > 0) {
- // HTTP header has been send and Server response header has been handled
- USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
- // file found at server
- if (httpCode == HTTP_CODE_OK) {
- //這里為接口訪問成功后執行內容
- String payload = http.getString();
- Serial.println("返回數據:" + urls);
- USE_SERIAL.println(payload);
- }
- } else {
-
- USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
- }
- http.end();
- }else{
- //這里可以寫訪問服務器失敗后的邏輯 不需要則去掉
- int ss = 1;
- }
- }
復制代碼
|