esp8266连接wifi的三种方式代码
时间: 2023-05-21 15:07:19 浏览: 1033
ESP8266WiFi探针代码
5星 · 资源好评率100%
以下是 esp8266 连接 WiFi 的三种方式的代码:
方式一:使用密码连接 Wi-Fi
```
#include <ESP8266WiFi.h>
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
void setup() {
Serial.begin(9600);
delay(10);
// Connect to Wi-Fi network with SSID and password
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// do nothing
}
```
方式二:使用 WPS 连接 Wi-Fi
```
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WiFiGeneric.h>
#define WPS_TIMEOUT 30
void setup() {
Serial.begin(9600);
Serial.println();
Serial.println("Starting WPS config");
WiFi.disconnect();
WiFi.mode(WIFI_STA);
Serial.println("WPS: START");
WiFi.beginWPSConfig();
Serial.print("WPS: WAIT");
int ticks = 0;
while (WiFi.status() != WL_CONNECTED && ticks++ < WPS_TIMEOUT) {
delay(1000);
Serial.print(".");
}
Serial.println();
if (WiFi.status() == WL_CONNECTED) {
Serial.println("WPS: Done!");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
else {
Serial.println("WPS: Timeout!");
}
}
void loop() {
// do nothing
}
```
方式三:使用 WiFiManager 一键连接 Wi-Fi
```
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
void setup() {
Serial.begin(115200);
WiFiManager wifiManager;
wifiManager.autoConnect("AP-NAME", "AP-PASSWORD");
Serial.println("WiFi Connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
// do nothing
}
```
注意:以上代码需要在 Arduino IDE 中安装相应的库才能正常运行,具体请参考相应的文档。
阅读全文