ESP8266开发笔记
生活随笔
收集整理的這篇文章主要介紹了
ESP8266开发笔记
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
ESP8266開發(fā)筆記
- ESP8266開發(fā)筆記
- 目前實現(xiàn)的功能
- 功能預(yù)覽
- 代碼
- Arduino代碼
- 服務(wù)器代碼
ESP8266開發(fā)筆記
今天是開始上手剛買的ESP8266模塊的第一天,剛有點進(jìn)展,現(xiàn)記錄如下。
目前實現(xiàn)的功能
今天剛上手開發(fā),查了不少資料,目前已經(jīng)實現(xiàn)的功能如下:
功能預(yù)覽
代碼
Arduino代碼
#include <Arduino.h> #include <ESP8266WiFi.h> #include <ESP8266WiFiMulti.h> #include <ESP8266HTTPClient.h> #include <ArduinoJson.h> #include <SPI.h> #include <string.h>// 定義工作波特率 #define BaudRate 115200// 設(shè)置 WiFi名和密碼 // Enter your Wi-Fi SSID const char *WIFINAME = "chen-2.4G"; // Enter you Wi-Fi Password const char *WIFIPW = "w88888888"; // 主機地址 const char *HOST = "192.168.1.199"; const unsigned int PORT = 8080;void setup() {Serial.begin(BaudRate); //Serial connectionSerial.println("ESP8266 Ready!");// Connecting to a WiFi networkSerial.print("Connect to ");Serial.println(WIFINAME);WiFi.begin(WIFINAME, WIFIPW); //WiFi connectionwhile (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI connection completiondelay(500);Serial.println("Waiting for connection");}Serial.println("WiFi connected");Serial.println("IP address: ");Serial.println(WiFi.localIP());Serial.println("");}void loop() {// 每隔多久取一次資料retrieveField(); // filed_id=1 是 DHT11 的溫度值delay(20000); // ms }void retrieveField() {// 設(shè)定 ESP8266 作為 Client 端WiFiClient client;// 設(shè)置超時時間client.setTimeout(10000);if (!client.connect(HOST, PORT)) {Serial.println("connection failed");return;} else {// 連接成功Serial.println(F("Connected!"));// Send HTTP requestclient.println(F("GET /testJson HTTP/1.0"));client.println(F("Host: 192.168.1.199"));client.println(F("Connection: close"));if (client.println() == 0) {Serial.println(F("Failed to send request"));return;}// Check HTTP statuschar status[32] = {0};client.readBytesUntil('\r', status, sizeof(status));Serial.println(status);if (strcmp(status, "HTTP/1.1 200 ") != 0) {Serial.print(F("Unexpected response: "));Serial.println(status);return;}// Skip HTTP headerschar endOfHeaders[] = "\r\n\r\n";if (!client.find(endOfHeaders)) {Serial.println(F("Invalid response"));return;}// Allocate the JSON document// Use arduinojson.org/v6/assistant to compute the capacity.const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;DynamicJsonDocument doc(capacity);// Parse JSON objectDeserializationError error = deserializeJson(doc, client);if (error) {Serial.print(F("deserializeJson() failed: "));Serial.println(error.c_str());return;}JsonObject root = doc.as<JsonObject>();// using C++11 syntax (preferred):for (JsonPair kv : root) {Serial.print(kv.key().c_str());Serial.print(" ---> ");const char *str = kv.value().as<char *>();if (str != NULL) {if (strlen(str) != 0) {// 這是一個字符串Serial.println(str);}} else {// 是數(shù)值Serial.println(kv.value().as<int>());}}// Extract values // Serial.println(F("Response:")); // Serial.println(doc["username"].as<char*>()); // Serial.println(doc["address"].as<char*>()); // Serial.println(doc["age"].as<int>());// Disconnectclient.stop();} }服務(wù)器代碼
服務(wù)器端代用Java構(gòu)建的一個簡單WEB項目,僅僅用于返回數(shù)據(jù)測試,可根據(jù)自己擅長替換!
package cn.fanchencloud.springbootwebtest.controller;import com.alibaba.fastjson.JSONObject; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map;/*** Created by handsome programmer.* User: chen* Date: 2020/3/22* Time: 22:28* Description:** @author chen*/ @RestController public class TestController {@RequestMapping(value = "/testJson", method = RequestMethod.GET)public Map<String, Object> testJson() {Map<String, Object> map = new HashMap<>(3);map.put("username", "fanchencloud");map.put("age", 24);map.put("address", "test address , 測試地址");return map;}/*** 功能描述:通過HttpServletRequest 的方式來獲取到j(luò)son的數(shù)據(jù)<br/>** @param request 請求數(shù)據(jù)* @return 請求結(jié)果*/@RequestMapping(value = "/test/data", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")public String getByRequest(HttpServletRequest request) {//獲取到JSONObjectJSONObject jsonParam = this.getJsonParam(request);// 將獲取的json數(shù)據(jù)封裝一層,然后在給返回JSONObject result = new JSONObject();result.put("msg", "ok");result.put("method", "request");result.put("data", jsonParam);return result.toJSONString();}/*** 功能描述:通過request來獲取到j(luò)son數(shù)據(jù)** @param request 請求數(shù)據(jù)* @return Json 對象*/public JSONObject getJsonParam(HttpServletRequest request) {JSONObject jsonParam = null;try {// 獲取輸入流BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));// 寫入數(shù)據(jù)到 StringBuilderStringBuilder sb = new StringBuilder();String line = null;while ((line = streamReader.readLine()) != null) {sb.append(line);}jsonParam = JSONObject.parseObject(sb.toString());// 直接將json信息打印出來System.out.println(jsonParam.toJSONString());} catch (Exception e) {e.printStackTrace();}return jsonParam;} }總結(jié)
以上是生活随笔為你收集整理的ESP8266开发笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 迷宫可达
- 下一篇: Vue实现Todo List