Fourth, the use of AP and STA mode of ESP32 single-chip wifi

Insert picture description here

Introduction to WIFI AP and STA

There are two modes in the WIFI of ESP32 that we need to know today, our usual wifi is the same, they are our theme today, AP mode and STA mode

AP mode, refers to the wireless access point, the mode of creating a wireless network. The router at home is the best example. The easy-to-understand AP mode is to create a wifi and then we use a mobile phone or other device to connect to the wifi. Refer to the mobile phone to open a hotspot, it may not be very accurate, but let’s understand it this way first

STA mode, every mobile phone connected to the hotspot can be called a STA site, that is, when our ESP32 works in STA mode, it can connect to the wifi sent by the router

If you want to have WIFI at home, you need to install a router. Then the router makes a WIFI. We use mobile phones and other devices to connect. In this process, we can understand that the router is in AP mode to create a wireless network, and the mobile phone is in STA mode to connect to the router. wireless network

ESP32 serial communication

Open the arduino compiler, create a new project, select the corresponding development board and port. I read the previous article and I won’t say much.
Before turning on the wifi function, I will briefly explain the use of the ESP32 serial port function, which is described in the arduino function reference . The two functions of serial communication need to learn to use

Serial.begin(speed)

Function function: initialize the UARTserial port and set the communication baud rate

The parameter speedis the baud rate parameter, the commonly used baud rates are 4800, 9600, 14400, 19200, 28800, 38400, 57600, 115200

Serial.print(val)

Function function: After initializing the serial port function, it is used to output data on the serial port

The parameter valis the data to be output

Let's create a new one to send a Hello World every three seconds! The program to the serial port is used as a demonstration, and the program is saved in the data file. The
code is as follows:

void setup() {
    
    
  // put your setup code here, to run once:
  Serial.begin(115200);  //初始化串口并设置波特率为115200
}

void loop() {
    
    
  // put your main code here, to run repeatedly:
  Serial.print("Holle World!\n");  //发送Holle World!到串口
  delay(3000);  //设置间隔3秒发送一次
}

The parameters of the serial port only need to be initialized and set once, so they are put in the setup function, and the sending data is a string type, so "" is added
. The \n in the data means the escape character and line break

Insert picture description here

AP and STA mode related functions

Before turning on the AP and STA modes of ESP32, we first see the introduction of some commonly used functions below, or you can skip it first, and wait for which function is used to see which function

AP related

WiFi.softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden, int max_connection)

Function function: used to set the wifi network information and start the AP mode. The

parameter
ssidis the name of the wifi network, the chartype data
passphrasesets the wifi password, if it can be empty, the set wifi is open without a password, the inttype data
channelsets the wifi channel, which can be set in 1~13it Choose between, do not fill in the parameter default 1, inttype data to
ssid_hiddenset whether wifi is hidden, set to 0not hide, 1hide, do not fill in the parameter default 0, booltype data to
max_connectionset the maximum number of devices that can be connected to the wifi, 1~4, inttype data


function return value boolType, start successfully returnture

WiFi.softAPConfig(IPAddress local_ip, IPAddress gateway, IPAddress subnet)

Function: Set the ESP32 IP地址, 网关地址, 子网掩码

parameters
local_ipfor the network to be set IP地址

gatewayfor the network to set the 网关地址
subnetnetwork needs to be set for 子网掩码
said parameter types are IPAddresstypes of parameters

function return value booltype, provided successful returnture

WiFi.softAPdisconnect(bool wifioff)

Function function: turn off AP mode or turn on the

parameter
wifioffas booltype data, the input tureis closed, the AP模式


function return value is booltype, and the setting is successful, it will returnture

WiFi.softAPIP()

Function function: ESP32 obtains the IP address of ESP32 itself after creating a wifi and returns the

function return value as IPAddresstype

WiFi.softAPmacAddress()

Function function: get the MAC地址type data of the function return value of the development board

String

WiFi.softAPgetStationNum()

Function function: return the number of connected wireless terminals, the

return value type of the function is uint8_ttype

STA related

wifi.begin(const char* ssid, const char *passphrase, int32_t channel, const uint8_t* bssid, bool connect)

Function function: The STA无线终端模式

parameters
ssidused const char*
to start the ESP32 development board are used to set the name of the wifi that needs to be connected, the parameter is the type data
passphraseto set the password of the wifi that needs to be connected, the parameter is the const char*type data
channelthe channel of the wifi to be connected, and it is the int32_ttype data. You can leave it blank
bssidas the MAC address to connect to wifi, which is the const uint8_t*data type. You can leave it blank to
connectset whether to connect to wifi, if yes ture, use the stored information to connect to wifi, if yes, the information falsewill be stored in the flash memory but not connected to wifi, the data is boolTypes of

wifi.config(IPAddress local_ip, IPAddress gateway, IPAddress subnet, IPAddress dns1, IPAddress dns2)

Function function: set ESP32 IP配置

parameters
local_ipfor configuration ESP32的固定IP地址, data for IPAddresstype
gatewayfor configuration 网关IP地址, data for IPAddresstype
subnetfor configuration 子网掩码, data for IPAddresstype
dns1and dns2optional parameters, which can be customized域名服务器的IP地址

WiFi.disconnect(bool wifioff, bool eraseap)

Function: Disconnect the network connection

parameter
wifioffsetting to tureturn off the ESP32's STA mode, set falseit to clear the SSID and password and disconnect the current connection, but not close the STA mode, and boolset the data type
eraseapto tureclear and save in Network parameters in Flash, the data is the booltype

WiFi.isConnected()

Function function: judge whether the network is connected and the

return value is tureif the connection is successful, falsethen the connection fails, and the return value is booltype

WiFi.setAutoReconnect(bool autoReconnect)

Function function: Set whether to automatically reconnect after the network is disconnected. The

parameter is
autoReconnectset to the turemodule will try to reconnect when it is disconnected, and it will falseremain disconnected when set to

WiFi.localIP()

Function function: return the current wireless terminal's IP address

data as IPAddresstype

WiFi.subnetMask()

Function function: return the subnet mask data of the current wireless terminal

as IPAddresstype

WiFi.gatewayIP()

Function function: return current gateway IP

data as IPAddresstype

WiFi.status()

Function function: return ESP32 connection status. The

return value is as follows
: 0: WL_IDLE_STATUSSwitching between WiFi working modes;
1: WL_NO_SSID_AVAILUnable to access the set SSID network;
2: WL_SCAN_COMPLETEDScanning completed;
3: WL_CONNECTEDConnection successful;
4: WL_CONNECT_FAILEDConnection failed;
5: WL_CONNECTION_LOSTConnection lost;
6: WL_DISCONNECTEDDisconnect;
255: WL_NO_SHIELDdon't care (designed to be compatible with WiFi Shield)

ESP32 turns on AP mode

When we use the AP or STA function of ESP32, we need to call the library WiFi.h, which contains the libraries needed to use the wifi function

Below we write an ESP32 to open the AP mode to create a wifi and output the name of the wifi and the IP address of the device through the serial port. We need to get in touch with two functions related to the use of the AP. You can also see the related functions above.

WiFi.softAP(const char* ssid, const char* passphrase, int channel, int ssid_hidden, int max_connection)

WiFi.softAPIP()

Below we see the code

#include<WiFi.h>  //调用包含wifi功能的库

const char *wifi_SSID="YXDZ_ESP32";  //保存AP的名称信息
const char *wifi_Password="ESP321234";  //保存AP的密码信息

void setup() {
    
    
  // put your setup code here, to run once:
  Serial.begin(115200);  //启动串口通信并设置波特率为115200
  
  WiFi.softAP(wifi_SSID,wifi_Password);  //设置AP模式热点的名称和密码,密码可不填则发出的热点为无密码热点

  Serial.print("\n ESP32建立的wifi名称为:");
  Serial.print(wifi_SSID);  //串口输出ESP32建立的wifi的名称
  Serial.print("\nESP32建立wifi的IP地址为:");
  Serial.print(WiFi.softAPIP());  //串口输出热点的IP地址
}

void loop() {
    
    
  // put your main code here, to run repeatedly:

}

Seeing the above code, we will find that the function involved in creating wifi in the whole program is only softAP(), and the others are more outputting debugging information. WiFi.softAPIP() also just obtains the IP address after ESP32 creates wifi, so we create The entire process of wifi only needs to call the wifi library and then fill in the name and password of the wifi to be created in softAP()

Next we verify whether our program is correct

1. Burn the program
2. Open the serial port assistant and press the reset button to view the IP address 192.168.4.1, everyone may be different
Insert picture description here
3. Find the wifi named YXDZ_ESP32, enter the password set in our program to connect (name and password are both Can be adjusted by yourself)

Insert picture description here
4. After connecting to wifi, we ping the IP address in cmd and communicate with ESP32 to make sure it can communicate

Insert picture description here
The above displayed sent=4, received=4, loss of 0% means normal communication is successful, the ip address in ping 192.168.4.1 is the ip address obtained by the serial port output on the board we obtained before, and we succeeded here. Open the AP mode of ESP32 and verify that there is no problem with communication

ESP32 turns on STA mode

Next we turn on the STA mode, the same need to call wifi.h, we will write an ESP32 to connect to the mobile phone hotspot and output the wifi name and development board IP address and other related debugging information through the serial port

Below we see several key functions that this program needs to use

WiFi.begin()ESP32 to set the configuration mode and the STA information of the name and password wifi connection
WiFi.status()for determining the wifi connection state
WiFi.SSID(), WiFi.localIP()used to obtain wifi, names and IP addresses ESP32 connection after the connection is successful

Post test code

#include<WiFi.h>

const char *wifi_SSID="OnePlus 8 Pro";  //设置连接的wifi名称信息
const char *wifi_Password="YXDZ1234";  //设置连接的wifi密码信息

void setup() {
    
    
  // put your setup code here, to run once:
  Serial.begin(115200);  //启动串口通信并设置波特率为115200

  WiFi.begin(wifi_SSID,wifi_Password);  //设置需要连接的wifi的名称和密码
  Serial.print("\n正在连接wifi");
  while(WiFi.status()!= WL_CONNECTED)  //启动连接,连到之前设置信息的wifi
  {
    
    
    delay(500);
    Serial.print(".");
    }
  Serial.print("\n已连接到wifi:");
  Serial.print(WiFi.SSID());  //输出WIFI的连接信息
  Serial.print("\nIP地址:");
  Serial.print(WiFi.localIP());  //输出WiFi的IP地址信息
}

void loop() {
    
    
  // put your main code here, to run repeatedly:

}

The above code first initializes the serial port to facilitate our debugging. After initializing the serial port, open the STA module to set the name and password of the connected wif (WiFi.begin() function). In the while statement, it is judged whether the wifi connection is successful. If the connection is successful, the loop is called. Behind is the code to output wifi name and IP address information

Similarly, we ping like the above AP mode to see if the data can be communicated.
First, burn the program to make sure the wifi connection is successful and obtain the IP address, open the tool serial monitor and press the reset button of ESP32 to connect to wifi

Insert picture description here
You can see that the ip address is 192.168.43.1, because it is a hotspot opened by a mobile phone. If the computer needs to communicate, it needs to be in the same local area network (that is, the computer is also connected to the mobile phone wifi). The
Insert picture description here
same ping in cmd just now Test the obtained IP address

Insert picture description here

to sum up

This issue mainly explains how to turn on the AP mode and STA mode of the ESP32 and the output of related information. In the next issue, we will start to learn about building a network server and interact with a computer and mobile phone. We will publish similar articles for a long time. Welcome to follow. The issue about ESP32 is here, please feel free to leave a message, if you need a program or information, you can also leave a message below!

Guess you like

Origin blog.csdn.net/qq_42250136/article/details/108680669