目的
使用ESP8266主要就是为了用它的网络功能。使用网络功能首先的就是需要连接到一个现有的网络(STA模式),或是建立一个网络(soft-AP模式)。
连接到网络
在Arduino for esp8266中连接到现有网络非常简单,直接上代码:
#include <ESP8266WiFi.h> //引入ESP8266Wifi库
void setup()
{
Serial.begin(115200);
Serial.println();
WiFi.begin("network-name", "pass-to-network"); //就只需要这一句就可以连接到一个网络了
//括号内参数分别为网络名称(SSID)和网络密码
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) //等待网络连接成功
{
delay(500);
Serial.print(".");
}
Serial.println();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP()); //通过串口打印输出模块在网络中的IP地址
}
void loop() {}
通过上面代码就可以方便的连接到一个网络,上传运行后可以在串口监视器中看到连接状态,连接成功后会打印输出IP地址,可以用处于同一网络下的电脑用ping指令ping该地址,如果ping通就说明网络连接确实已经成功了。
更多详细内容可以参考如下:
简单示例:
https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/readme.html#quick-start
STA模式进阶示例:
https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-examples.html
STA模式库说明:
https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/station-class.html
建立新网络
建立网络也非常简单,直接上代码:
#include <ESP8266WiFi.h> //引入ESP8266Wifi库
void setup()
{
Serial.begin(115200);
Serial.println();
Serial.print("Setting soft-AP ... ");
//就只需要下面这一句就可以建立一个网络了
//输入参数分别了网络名称和密码
boolean result = WiFi.softAP("ESPsoftAP_01", "pass-to-soft-AP");
if(result == true) //如果建立成功就打印输出“Ready”
{
Serial.println("Ready");
}
else
{
Serial.println("Failed!");
}
}
void loop()
{
//打印输出当前有多少设备连接到ESP8266建立的网络中
Serial.printf("Stations connected = %d\n", WiFi.softAPgetStationNum());
delay(3000);
}
通过上面代码就可以快速的建立一个新的网络,可以将电脑连接到该网络中,然后通过ping指令测试网络连接(AP模式下ESP8266默认IP地址是192.168.4.1)。
注:ESP8266建立的网络只支持5个设备同时接入。
更多详细内容可以参考如下:
AP模式示例:
https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/soft-access-point-examples.html
AP模式库说明:
https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/soft-access-point-class.html
更多方式
等待被写入
总结
使用Arduino for esp8266可以非常简单的完成网络功能的最基础步骤,接下来就可以进行真正的网络的应用了。