前言:
鉴于项目需要,决定把wifi类的官方例程全看一遍,并同步更新到博客上
代码:
/*
* 该例程向一个TCP服务器发送信息
*
*/
#include <WiFi.h>
#include <WiFiMulti.h>
WiFiMulti WiFiMulti;
void setup()
{
Serial.begin(115200);
delay(10);
// 连接wifi
WiFiMulti.addAP("wifi名称", "wifi密码");
Serial.println();
Serial.println();
Serial.print("连接中... ");
while(WiFiMulti.run() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("");
Serial.println("WiFi 已连接");
Serial.println("IP: ");
Serial.println(WiFi.localIP());
delay(500);
}
void loop()
{
// const uint16_t port = 80;
// const char * host = "www.baidu.com"; // ip or dns
const uint16_t port = 80; //一般网站默认开放端口为80
const char * host = "www.baidu.com"; // ip or dns,用百度做测试
Serial.print("Connecting to ");
Serial.println(host);
// 用 WiFiClient 类以创建TCP连接
WiFiClient client;
if (!client.connect(host, port)) {
Serial.println("Connection failed.");
Serial.println("Waiting 5 seconds before retrying...");
delay(5000);
return;
}
// 将会向服务器发送请求
//取消下行注释,即可将任意字符串发送到服务器
//client.print("Send this data to the server");
//取消下行注释,发送一个基本的文档请求到服务器
client.print("GET /index.html HTTP/1.1\n\n");
int maxloops = 0;
//等待服务器响应
while (!client.available() && maxloops < 1000)
{
maxloops++;
delay(1); //延时 1 ms
}
if (client.available() > 0)
{
//读取服务器响应内容
while(client.available()) { //检测接收缓存区是否有内容
String line = client.readStringUntil('\r');
Serial.print(line);
}
}
else
{
Serial.println("client.available() timed out ");
}
Serial.println("关闭连接");
client.stop();
Serial.println("再程序循环前等待5s...");
delay(5000);
}
运行效果: