Esp32中Wi-Fi 开发介绍及使用:AP模式与STA模式常用函数详解

目录

一、介绍

二、AP模式下常用函数

1.将 Wi-Fi 作为接入点启动。

2.使用函数 softAP 配置 Wi-Fi AP 特性:

3.使用函数softAPConfig配置静态IP、网关、子网掩码

4.使用函数softAPdisconnect强制断开AP连接

5.使用函数softAPgetStationNum获取连接到AP的客户端数量

6.获取AP的IPv4地址

7.获取 AP IPv4 广播地址

8.获取AP的network ID

9.获取AP的子网网段

10.获取AP的子网掩码

11.启用IPv6

12.获取IPv6地址

13.获取AP主机名

14.设置AP主机名

15.设置AP的MAC地址(如果某些特定情况下需要自定义mac地址)

16.获取设置的AP的MAC地址

17.获取AP的SSID

三、AP模式示例代码

四、STA模式下常用函数

1.连接WiFi

2.连接wifi

3.用config设置wifi配置

4.重连

5.断开连接

6.判断是否连接

7.设置自动连接

8.连接丢失时自动重连

9.将 AP 的最低安全性设置为可连接

10.多无线连接WiFiMulti

11.wifi扫描WiFiScan

五、Wifi STA示例代码

六、参考资料


一、介绍

Wi-Fi API 提供对 802.11b/g/n 协议驱动程序的支持。支持以下四种模式

基站模式(即STA模式或Wi-Fi客户端模式),此时ESP32连接到接入点(AP);

AP模式(即Soft-AP模式或接入点模式),此时基站连接到ESP32;

AP-STA共存模式(ESP32既是接入点,同时又作为基站连接到另外一个接入点);

AP-STA混合模式(ESP32既是接入点,同时又作为基站连接到另外一个接入点,且该接入点也有一个或多个客户端连接)。

二、AP模式下常用函数

1.将 Wi-Fi 作为接入点启动。

WiFi.softAP(ssid, password);

2.使用函数 softAP 配置 Wi-Fi AP 特性:

bool softAP(const char* ssid, const char* passphrase = NULL, int channel = 1, int ssid_hidden = 0, int max_connection = 4, bool ftm_responder = false);
  • ssid 设置 Wi-Fi 网络 SSID。
  • passphrase 设置 Wi-Fi 网络密码。如果网络时开放的,则设置为 NULL。
  • channel 配置 Wi-Fi 信道.Wi-Fi信道是指无线网络中传输数据的通道,类似于有线网络中的电缆。 信道的带宽是固定的,而且在同一时间内只能有一个设备使用该信道。如果两个设备同时使用相同的信道,则会发生干扰,从而降低信号质量。
  • ssid_hidden 将网络设置为隐藏
  • max_connection 设置最大同时连接数。默认值为 4。
  • ftm_responder 设置 Wi-Fi FTM 响应程序功能。仅适用于 ESP32-S2 和 ESP32-C3 SoC!

如果配置成功,则返回 true。

3.使用函数softAPConfig配置静态IP、网关、子网掩码

bool softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet);

local_ip IP地址        gateway 网关        subnet 子网掩码

如果配置成功,则返回 true。

4.使用函数softAPdisconnect强制断开AP连接

bool softAPdisconnect(bool wifioff = false);

wifioff 设置位true时断开连接

如果配置成功,该函数将返回 true。

5.使用函数softAPgetStationNum获取连接到AP的客户端数量

uint8_t softAPgetStationNum();

6.获取AP的IPv4地址

IPAddress softAPIP();

7.获取 AP IPv4 广播地址

IPAddress softAPBroadcastIP();

8.获取AP的network ID

IPAddress softAPNetworkID();

该函数将以 IPAddress 格式返回 AP 网络地址。

9.获取AP的子网网段

uint8_t softAPSubnetCIDR();

10.获取AP的子网掩码

IPAddress softAPSubnetMask();

11.启用IPv6

bool softAPenableIpV6();

如果配置成功,该函数将返回 true。

12.获取IPv6地址

IPv6Address softAPIPv6();

该函数将以 IPv6 地址格式返回 AP IPv6 地址。

13.获取AP主机名

const char * softAPgetHostname();

14.设置AP主机名

bool softAPsetHostname(const char * hostname);

如果配置成功,该函数将返回 true。

15.设置AP的MAC地址(如果某些特定情况下需要自定义mac地址)

uint8_t* softAPmacAddress(uint8_t* mac);

16.获取设置的AP的MAC地址

String softAPmacAddress(void);

17.获取AP的SSID

String softAPSSID(void) const;

三、AP模式示例代码

#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiAP.h>

#define LED_BUILTIN 2   // Set the GPIO pin where you connected your test LED or comment this line out if your dev board has a built-in LED

// Set these to your desired credentials.
const char *ssid = "yourAP";
const char *password = "yourPassword";

WiFiServer server(80);


void setup() {
  pinMode(LED_BUILTIN, OUTPUT);

  Serial.begin(115200);
  Serial.println();
  Serial.println("Configuring access point...");

  // You can remove the password parameter if you want the AP to be open.
  // a valid password must have more than 7 characters
  if (!WiFi.softAP(ssid, password)) {
    log_e("Soft AP creation failed.");
    while(1);
  }
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.begin();

  Serial.println("Server started");
}

void loop() {
  WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    Serial.println("New Client.");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();

            // the content of the HTTP response follows the header:
            client.print("Click <a href=\"/H\">here</a> to turn ON the LED.<br>");
            client.print("Click <a href=\"/L\">here</a> to turn OFF the LED.<br>");

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          } else {    // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }

        // Check to see if the client request was "GET /H" or "GET /L":
        if (currentLine.endsWith("GET /H")) {
          digitalWrite(LED_BUILTIN, HIGH);               // GET /H turns the LED on
        }
        if (currentLine.endsWith("GET /L")) {
          digitalWrite(LED_BUILTIN, LOW);                // GET /L turns the LED off
        }
      }
    }
    // close the connection:
    client.stop();
    Serial.println("Client Disconnected.");
  }
}

四、STA模式下常用函数

1.连接WiFi

WiFi.begin(ssid, password);

检查WiFi的状态

while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
}

连接出成果后可以打印网络的IP地址

Serial.println("IP address: ");
Serial.println(WiFi.localIP());

2.连接wifi

wl_status_t begin(const char* ssid, const char *passphrase = NULL, int32_t channel = 0, const uint8_t* bssid = NULL, bool connect = true);

或者

wl_status_t begin(char* ssid, char *passphrase = NULL, int32_t channel = 0, const uint8_t* bssid = NULL, bool connect = true);


ssid AP的SSID

passphrase 密码,如果时开放网络则设置NULL

channel 设置WiFi信道

uint8_t* bssid 设置AP无线射频的MAC地址(48位),是每个BSS的唯一标识符

connect 设置为 true 以自动连接到配置的网络.


3.用config设置wifi配置

bool config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1 = (uint32_t)0x00000000, IPAddress dns2 = (uint32_t)0x00000000);


local_ip ip地址        gateway 网关        subnet 子网掩码        dns1 dns        dns2 备用dns

如果配置成功,该函数将返回 true。

IPAddress 格式由 4 个字节定义,如下所述:

IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet);

例如

IPAddress local_ip(192, 168, 10, 20);

4.重连

bool reconnect();

5.断开连接

bool disconnect(bool wifioff = false, bool eraseap = false);

wifioff 使用true关闭wifi连接

eraseap 使用 true 从 NVS 内存中擦除 AP 配置。

6.判断是否连接

bool isConnected();

7.设置自动连接

bool setAutoReconnect(bool autoReconnect);

8.连接丢失时自动重连

bool getAutoReconnect();

如果启用此设置,该函数将返回 true

9.将 AP 的最低安全性设置为可连接

bool setMinSecurity(wifi_auth_mode_t minSecurity);

minSecurity 是 AP 被视为可连接的最低安全性。默认值为WIFI_AUTH_WPA2_PSK

10.多无线连接WiFiMulti

支持连接多个ap,以下添加要连接的ap

bool addAP(const char* ssid, const char *passphrase = NULL);

用run函数运行

uint8_t run(uint32_t connectTimeout=5000);

多WiFi连接的例子

#include <WiFi.h>
#include <WiFiMulti.h>

WiFiMulti wifiMulti;

void setup()
{
    Serial.begin(115200);
    delay(10);

    wifiMulti.addAP("ssid_from_AP_1", "your_password_for_AP_1");
    wifiMulti.addAP("ssid_from_AP_2", "your_password_for_AP_2");
    wifiMulti.addAP("ssid_from_AP_3", "your_password_for_AP_3");

    Serial.println("Connecting Wifi...");
    if(wifiMulti.run() == WL_CONNECTED) {
        Serial.println("");
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
    }
}

void loop()
{
    if(wifiMulti.run() != WL_CONNECTED) {
        Serial.println("WiFi not connected!");
        delay(1000);
    }
}

11.wifi扫描WiFiScan

int16_t scanNetworks(bool async = false, bool show_hidden = false, bool passive = false, uint32_t max_ms_per_chan = 300, uint8_t channel = 0);

调用以获取异步模式下的扫描状态。

int16_t scanComplete();

从 RAM 中删除上次扫描结果。

void scanDelete();

将所有信息从扫描的 wifi 加载到 ptr 参数中。

bool getNetworkInfo(uint8_t networkItem, String &ssid, uint8_t &encryptionType, int32_t &RSSI, uint8_t* &BSSID, int32_t &channel);

wifi扫描例子

#include "WiFi.h"

void setup()
{
    Serial.begin(115200);

    // Set WiFi to station mode and disconnect from an AP if it was previously connected.
    WiFi.mode(WIFI_STA);
    WiFi.disconnect();
    delay(100);

    Serial.println("Setup done");
}

void loop()
{
    Serial.println("Scan start");

    // WiFi.scanNetworks will return the number of networks found.
    int n = WiFi.scanNetworks();
    Serial.println("Scan done");
    if (n == 0) {
        Serial.println("no networks found");
    } else {
        Serial.print(n);
        Serial.println(" networks found");
        Serial.println("Nr | SSID                             | RSSI | CH | Encryption");
        for (int i = 0; i < n; ++i) {
            // Print SSID and RSSI for each network found
            Serial.printf("%2d",i + 1);
            Serial.print(" | ");
            Serial.printf("%-32.32s", WiFi.SSID(i).c_str());
            Serial.print(" | ");
            Serial.printf("%4d", WiFi.RSSI(i));
            Serial.print(" | ");
            Serial.printf("%2d", WiFi.channel(i));
            Serial.print(" | ");
            switch (WiFi.encryptionType(i))
            {
            case WIFI_AUTH_OPEN:
                Serial.print("open");
                break;
            case WIFI_AUTH_WEP:
                Serial.print("WEP");
                break;
            case WIFI_AUTH_WPA_PSK:
                Serial.print("WPA");
                break;
            case WIFI_AUTH_WPA2_PSK:
                Serial.print("WPA2");
                break;
            case WIFI_AUTH_WPA_WPA2_PSK:
                Serial.print("WPA+WPA2");
                break;
            case WIFI_AUTH_WPA2_ENTERPRISE:
                Serial.print("WPA2-EAP");
                break;
            case WIFI_AUTH_WPA3_PSK:
                Serial.print("WPA3");
                break;
            case WIFI_AUTH_WPA2_WPA3_PSK:
                Serial.print("WPA2+WPA3");
                break;
            case WIFI_AUTH_WAPI_PSK:
                Serial.print("WAPI");
                break;
            default:
                Serial.print("unknown");
            }
            Serial.println();
            delay(10);
        }
    }
    Serial.println("");

    // Delete the scan result to free memory for code below.
    WiFi.scanDelete();

    // Wait a bit before scanning again.
    delay(5000);
}

五、Wifi STA示例代码


#include <WiFi.h>

const char* ssid     = "your-ssid"; // Change this to your WiFi SSID
const char* password = "your-password"; // Change this to your WiFi password

const char* host = "api.thingspeak.com"; // This should not be changed
const int httpPort = 80; // This should not be changed
const String channelID   = "2005329"; // Change this to your channel ID
const String writeApiKey = "V6YOTILH9I7D51F9"; // Change this to your Write API key
const String readApiKey = "34W6LGLIFXD56MPM"; // Change this to your Read API key

// The default example accepts one data filed named "field1"
// For your own server you can ofcourse create more of them.
int field1 = 0;

int numberOfResults = 3; // Number of results to be read
int fieldNumber = 1; // Field number which will be read out

void setup()
{
    Serial.begin(115200);
    while(!Serial){delay(100);}

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println("******************************************************");
    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 readResponse(WiFiClient *client){
  unsigned long timeout = millis();
  while(client->available() == 0){
    if(millis() - timeout > 5000){
      Serial.println(">>> Client Timeout !");
      client->stop();
      return;
    }
  }

  // Read all the lines of the reply from server and print them to Serial
  while(client->available()) {
    String line = client->readStringUntil('\r');
    Serial.print(line);
  }

  Serial.printf("\nClosing connection\n\n");
}

void loop(){
  WiFiClient client;
  String footer = String(" HTTP/1.1\r\n") + "Host: " + String(host) + "\r\n" + "Connection: close\r\n\r\n";

  // WRITE --------------------------------------------------------------------------------------------
  if (!client.connect(host, httpPort)) {
    return;
  }

  client.print("GET /update?api_key=" + writeApiKey + "&field1=" + field1 + footer);
  readResponse(&client);

  // READ --------------------------------------------------------------------------------------------

  String readRequest = "GET /channels/" + channelID + "/fields/" + fieldNumber + ".json?results=" + numberOfResults + " HTTP/1.1\r\n" +
                       "Host: " + host + "\r\n" +
                       "Connection: close\r\n\r\n";

  if (!client.connect(host, httpPort)) {
    return;
  }

  client.print(readRequest);
  readResponse(&client);

  // -------------------------------------------------------------------------------------------------

  ++field1;
  delay(10000);
}

六、参考资料

ESP32 Arduino Core’s documentation

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值