一、ESP8266簡介
ESP8266 是深圳安信可科技有限公司開發的基於樂鑫ESP8266的超低功耗的UART-WIFI模塊的模組,可以方便進行二次元開發,接入雲端服務,實現手機3/4G全球隨時隨地的控制,加速產品原型設計。
核心模塊處理器ESP8266在較小尺寸中繼承了業界領先的Tensilical106超低功耗32位微型MCU,帶有16位精簡模式,支持RTOS(實時操作系統,指當外界事件或者數據變化時候能夠以足夠快的速度處理),集成WIFI/MAC/BB/RF/PA/LAN,板載天線。支持IEEE802.11b/g/n協議,完整的TCP/IP協議。
二、開發環境
開發環境采用Arduino IDE for ESP8266 采用 Arduino 語法進行編程設計。
三、編程
1. HTTP相關知識
HTTP是一套計算機網絡通訊規則。下來主要介紹一下HTTP消息格式。詳細HTTP請求請戳鏈接。
HTTP請求數據格式:
當瀏覽器發送請求是,向服務器發送了一個數據塊,也就是請求信息,其中信息由三部分組成。
1. 請求方法 URI協議/版本
2. 請求頭(Request Header)
3. 請求正文
eg.
1 GET/sample.jspHTTP/1.1
2 Accept:image/gif.image/jpeg,*/*
3 Accept-Language:zh-cn 4 Connection:Keep-Alive 5 Host:localhost 6 User-Agent:Mozila/4.0(compatible;MSIE5.01;Window NT5.0) 7 Accept-Encoding:gzip,deflate 8
9 username=jinqiao&password=1234
HTTP 請求應答格式:
當服務器收到瀏覽器的請求時,會向客戶端返回數據,數據主要由三部分組成
1. 協議狀態 版綳帶嗎描述
2. 響應頭(ResponseHeader)
3. 響應正文
eg.
1 HTTP/1.1 200 OK 2 Server:Apache Tomcat/5.0.12
3 Date:Mon,6Oct2003 13:23:42 GMT 4 Content-Length:112
5
6 data(返回數據)
2. ESP8266 編程
下附esp8266模塊發送請求的代碼
1 /*
2 * HTTP over TLS (HTTPS) example sketch 3 * 4 * This example demonstrates how to use 5 * WiFiClientSecure class to access HTTPS API. 6 * We fetch and display the status of 7 * esp8266/Arduino project continous integration 8 * build. 9 * 10 * Created by Ivan Grokhotkov, 2015. 11 * This example is in public domain. 12 */
13
14 #include <ESP8266WiFi.h>
15 #include <WiFiClientSecure.h>
16
17 const char* ssid = "zlei"; 18 const char* password = "18829237005"; 19
20 const char* host = "15r34407v7.imwork.net"; //需要訪問的域名
21 const int httpsPort = 37170; // 需要訪問的端口
22 const String url = "/test"; // 需要訪問的地址
23
24 void setup() { 25 Serial.begin(9600); 26 Serial.println(); 27 Serial.print("connecting to "); 28 Serial.println(ssid); 29 WiFi.begin(ssid, password); // 連接WIFI
30 while (WiFi.status() != WL_CONNECTED) { 31 delay(500); 32 Serial.print("."); 33 } 34 Serial.println(""); 35 Serial.println("WiFi connected"); 36 Serial.println("IP address: "); 37 Serial.println(WiFi.localIP()); // 顯示WIFI地址
38 } 39
40 void loop() { 41 Serial.print("connecting to "); 42 Serial.println(host); 43
44 WiFiClient client; 45
46 /** 47 * 測試是否正常連接 48 */
49 if (!client.connect(host, httpsPort)) { 50 Serial.println("connection failed"); 51 return; 52 } 53 delay(10); 54
55 String postRequest =(String)("GET ") + url + "/ HTTP/1.1\r\n" +
56 "Content-Type: text/html;charset=utf-8\r\n" +
57 "Host: " + host + "\r\n" +
58 "User-Agent: BuildFailureDetectorESP8266\r\n" +
59 "Connection: Keep Alive\r\n\r\n"; 60 Serial.println(postRequest); 61 client.print(postRequest); // 發送HTTP請求
62
63 /** 64 * 展示返回的所有信息 65 */
66 String line = client.readStringUntil('\n'); 67 while(line.length() != 0){ 68 Serial.println(line); 69 line = client.readStringUntil('\n'); 70 } 71 Serial.println(line); 72 client.stop(); 73 delay(3000); 74 }
總結: 通過 WiFiClient 的 connect 方法來進行WIFI鏈接 通過print方法來發送HTTP請求, 以及readStringUntil('\n') 來讀取服務器端返回的數據。
其中測試結果如圖所示:
、
如有錯誤,歡迎指正。