硬件环境:Mac,ArduinoUNO,ESP8266-01模块
软件环境:arduino-1.8.12-macosx
相关手动操作参考前文:http://www.gaohaiyan.com/2573.html
服务端使用最简单的代码
1 2 3 4 5 |
<?php header("Content-Type: text/html; charset=utf-8"); echo '{"note":"hello esp8266 !"}'; ?> |
这是示例代码,将之保存为php文件放到一个php的服务器或空间里。
esp8266代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
/** 此代码烧录在esp8266模块中 */ #include <ESP8266WiFi.h> const char *ssid = "WifiName"; const char *password = "wifipassword"; const char *host = "www.baidu.com"; const int port = 80; void setup(void) { Serial.begin(115200); // WiFi.mode(WIFI_AP); // 设置模块作为服务端模式,类似无线路由器,发送热点供其它设备连接 WiFi.mode(WIFI_STA); // 设置模块作为客户端模式,类似普通网卡,连接wifi热点 WiFi.begin(ssid, password); // 连接某个热点 while (WiFi.status() != WL_CONNECTED) { // 判断连接成功 delay(500); Serial.print("."); } Serial.println(""); Serial.print("连接到热点:"); Serial.println(ssid); Serial.print("本地IP: "); Serial.println(WiFi.localIP()); Serial.println(); Serial.println(); } void loop(void) { WiFiClient client; while (!client.connect(host, port)) { // 连接服务器 Serial.println("连接服务端失败"); delay(100); } Serial.print("连接到服务端:"); Serial.println(host); String request = String("GET ") + "/接口url/接口.php" + "/ HTTP/1.1\r\n" + // GET请求,接口url "Content-Type: text/html;charset=utf-8\r\n" + "Host: " + host + ":" + port + "\r\n" + // 主机+端口 "User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36\r\n" + "Connection: Keep Alive\r\n"; // 参数结尾是 \r\n client.println(request); // 访问接口。这里使用的是println即数据末尾再加 \r\n delay(100); String result = ""; while (client.connected() || client.available()) { // 接口响应 String line = client.readStringUntil('\n'); if (line.length() > 0) { result += line + "\r\n"; } } Serial.println("服务端返回:" + result); client.stop(); // 断开连接 delay(2000); } |
如下图,通过ArduinoIDE的串口监视器看到的访问反馈:
-end
声明
本文由崔维友 威格灵 cuiweiyou vigiles cuiweiyou 原创,转载请注明出处:http://www.gaohaiyan.com/2601.html
承接App定制、企业web站点、办公系统软件 设计开发,外包项目,毕设