ESP8266/WemosD1开发板联网教程 Arduino程序,相关物联网功能直接往标注的地方加内容就行了,拿来配置好环境即能用,保姆级注释
一 、实现功能:通过开发板检测mq3传感器数据,连接周围Wifi,向云服务器发送数据/请求数据。
二 、设备工具:
1、ESP8266/WemosD1开发板 (Arduino其他开发板连接esp8266模块也可以)
2、服务器接口
电路原理图如下:
三、代码:
- #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;
- }
- }
复制代码
|