The Wi-Fi API provides support for the 802.11b/g/n protocol driver. This API includes:
Station mode (STA mode or Wi-Fi client mode). ESP32 connects to an access point
AP mode (aka Soft-AP mode or Access Point mode). Devices connect to the ESP32
Security modes (WPA2, WPA3 etc.)
Scanning for access points
In this mode, the ESP32 is configured as an Access Point (AP) and it’s capable of receiving incoming connections from other devices (stations) by providing a Wi-Fi network.
This mode can be used for serving an HTTP or HTTPS server inside the ESP32, for example.
The STA mode is used to connect the ESP32 to a Wi-Fi network, provided by an Access Point.
This is the mode to be used if you want to connect your project to the Internet.
Here is the description of the WiFi API.
Here are the common APIs that are used for both modes, AP and STA.
/*F******************************************************************** * set the memory allocation mode for the Wi-Fi buffers. **********************************************************************/ static void useStaticBuffers( bool bufferMode ); Set true to use the Wi-Fi buffers memory allocation as static Set false to set the buffers memory allocation to dynamic. The use of dynamic allocation is recommended to save memory and reduce resources usage. However, the dynamic performs slightly slower than the static allocation. Use static allocation if you want to have more performance and if your application is multi-tasking. By default, the memory allocation will be set to dynamic if this function is not being used.
/*F******************************************************************** * Configures the Dual antenna functionallity. This function should be used only on the ESP32-WROOM-DA module or any other ESP32 with RF switch. **********************************************************************/ bool setDualAntennaConfig( uint8_t gpio_ant1, uint8_t gpio_ant2 , wifi_rx_ant_t rx_mode, wifi_tx_ant_t tx_mode ); gpio_ant1 Configure the GPIO number for the antenna 1 connected to the RF switch (default GPIO2 on ESP32-WROOM-DA) gpio_ant2 Configure the GPIO number for the antenna 2 connected to the RF switch (default GPIO25 on ESP32-WROOM-DA) rx_mode Set the RX antenna mode. See wifi_rx_ant_t for the options. tx_mode Set the TX antenna mode. See wifi_tx_ant_t for the options. Return true if the configuration was successful. For the rx_mode you can use the following configuration: WIFI_RX_ANT0 Selects the antenna 1 for all RX activity. WIFI_RX_ANT1 Selects the antenna 2 for all RX activity. WIFI_RX_ANT_AUTO Selects the antenna for RX automatically. For the tx_mode you can use the following configuration: WIFI_TX_ANT0 Selects the antenna 1 for all TX activity. WIFI_TX_ANT1 Selects the antenna 2 for all TX activity. WIFI_TX_ANT_AUTO Selects the antenna for TX automatically.
The WiFiAP is used to configure and manage the Wi-Fi as an Access Point. This is where you can find the related functions for the AP.
/*F******************************************************************** * start the Wi-Fi as an Access Point. **********************************************************************/ WiFi.softAP( ssid, password ); Please see the full WiFiAP example in: ap example .
/*F******************************************************************** * configure the Wi-Fi AP characteristics: **********************************************************************/ bool softAP( const char *ssid, const char *passphrase = NULL, int channel = 1 , int ssid_hidden = 0, int max_connection = 4, bool ftm_responder = false); Where: ssid: sets the Wi-Fi network SSID. passphrase: sets the Wi-Fi network password. If the network is open, set as NULL. channel: configures the Wi-Fi channel. ssid_hidden: sets the network as hidden. max_connection: sets the maximum number of simultaneous connections. Default is 4. ftm_responder: sets the Wi-Fi FTM responder feature. Only for ESP32-S2 and ESP32-C3 SoC! Return true if the configuration was successful.
/*F******************************************************************** * configure the IP as static (fixed) as well as the gateway and subnet. **********************************************************************/ bool softAPConfig( IPAddress local_ip, IPAddress gateway, IPAddress subnet ); Where: local_ip: sets the local IP address. gateway: sets the gateway IP. subnet: sets the subnet mask. Returns true: if the configuration is successful.
/*F******************************************************************** * force the AP disconnection. **********************************************************************/ bool softAPdisconnect( bool wifioff = false ); Where: wifioff: sets the Wi-Fi off if true . The function will return true if the configuration is successful.
/*F******************************************************************** * returns the number of clients connected to the AP. **********************************************************************/ uint8_t softAPgetStationNum();
/*F******************************************************************** * get the AP IPv4 address. **********************************************************************/ IPAddress softAPIP(); The function will return the AP IP address in IPAddress format.
/*F******************************************************************** * get the AP IPv4 broadcast address. **********************************************************************/ IPAddress softAPBroadcastIP(); Returns the AP broadcast address in IPAddress format.
/*F******************************************************************** * Get the softAP network ID. **********************************************************************/ IPAddress softAPNetworkID(); Returns the AP network address in IPAddress format.
/*F******************************************************************** * Get the softAP subnet CIDR. **********************************************************************/ uint8_t softAPSubnetCIDR();
/*F******************************************************************** * enable the IPv6 support. **********************************************************************/ bool softAPenableIpV6(); Returns true if the configuration is successful.
/*F******************************************************************** * get the IPv6 address. **********************************************************************/ softAPIPv6(); Returns the AP IPv6 address in IPv6Address format.
/*F******************************************************************** * get the AP hostname. **********************************************************************/ const char* softAPgetHostname();
/*F******************************************************************** * set the AP hostname. **********************************************************************/ bool softAPsetHostname( const char * hostname ); Where: hostname sets the device hostname. Returns: true if the configuration is successful.
/*F******************************************************************** * define the AP MAC address. **********************************************************************/ uint8_t* softAPmacAddress( uint8_t* mac ); Where: mac sets the new MAC address. /*F******************************************************************** * get AP MAC address **********************************************************************/ softAPmacAddress( void );
/*F******************************************************************** * get the AP SSID. **********************************************************************/ String softAPSSID( void ) const; Returns the AP SSID.
/*F******************************************************************** * The WiFiSTA is used to configure and manage the Wi-Fi as Station. The related functions for the STA are here. **********************************************************************/
The following code shows the basic usage of the WifiSTA functionality.WiFi.begin( ssid, password );Where the ssid and password are for the network you want to connect the ESP32. To check if the connection is successful, you can use:WiFi.status() != WL_CONNECTED) { delay( 500 ); Serial. print("."); }After a successful connection, you can print the IP address given by the network.Serial.println( "IP address: " ); Serial.println( WiFi. localIP() ); Please see the full example of the WiFiSTA in: sta example .
STA Configurationbegin/*F******************************************************************** * Functions begin are used to configure and start the Wi-Fi. **********************************************************************/ begin( const char *ssid, const char *passphrase = NULL, int32_t channel = 0 , const uint8_t* bssid = NULL, bool connect = true); Where: ssid: sets the AP SSID. passphrase: sets the AP password. Set as NULL for open networks. connect: sets true to connect to the configured network automatically. /*F******************************************************************** * **********************************************************************/ begin( char* ssid, char *passphrase = NULL, int32_t channel = 0 , const uint8_t* bssid = NULL, bool connect = true); Where: ssid: sets the AP SSID. passphrase: sets the AP password. Set as for open networks. channel: sets the Wi-Fi channel. bssid: sets the AP BSSID. connect: sets true to connect to the configured network automatically. /*F******************************************************************** * start the connection after being configured. **********************************************************************/ begin();
/*F******************************************************************** * configure Wi-Fi. After configuring, you can call function begin to start the Wi-Fi process. **********************************************************************/ config()/*F******************************************************************** * **********************************************************************/ bool config( IPAddress local_ip, IPAddress gateway, IPAddress subnet , IPAddress dns1 = (uint32_t)0x00000000 , IPAddress dns2 = (uint32_t)0x00000000); Where: local_ip: sets the local IP. gateway: sets the gateway IP. subnet: sets the subnet mask. dns1: sets the DNS. dns2: sets the DNS alternative option. Returns: true if the configuration is successful.
The IPAddress format is defined by 4 bytes as described here:IPAddress( uint8_t first_octet, uint8_t second_octet, uint8_t third_octet , uint8_t fourth_octet);Example:
IPAddress local_ip( 192, 168, 10, 20);See the WiFiClientStaticIP.ino for more details on how to use this feature.
STA ConnectionreconnectFunction used to reconnect the Wi-Fi connection.
bool reconnect();disconnectFunction to force disconnection.
bool disconnect( bool wifioff = false, bool eraseap = false);Where:
wifioff use true to turn the Wi-Fi radio off.
eraseap use true to erase the AP configuration from the NVS memory.
The function will return true if the configuration is successful.
Function used to get the connection state.
bool isConnected();
Return the connection state.
Function is deprecated.
Function is deprecated.
Function used to set the automatic reconnection if the connection is lost.
bool setAutoReconnect( bool autoReconnect);
Where:
autoConnect is set to true to enable this option.
Function used to get the automatic reconnection if the connection is lost.
bool getAutoReconnect();
The function will return true if this setting is enabled.
Function used to set the minimum security for AP to be considered connectable.
bool setMinSecurity(wifi_auth_mode_t minSecurity);
Where:
The WiFiMulti allows you to add more than one option for the AP connection while running as a station.
To add the AP, use the following function. You can add multiple AP’s and this library will handle the connection.
bool addAP( const char *ssid, const char *passphrase = NULL);
After adding the AP’s, run by the following function.
uint8_t run( uint32_t connectTimeout= 5000);
To see how to use the WiFiMulti , take a look at the WiFiMulti.ino example available.
To perform the Wi-Fi scan for networks, you can use the following functions:
Start scan WiFi networks available.
int16_t scanNetworks( bool async = false, bool show_hidden = false , bool passive = false, uint32_t max_ms_per_chan = 300 , uint8_t channel = 0);
Called to get the scan state in Async mode.
int16_t scanComplete();
Delete last scan result from RAM.
void scanDelete();
Loads all infos from a scanned wifi in to the ptr parameters.
bool getNetworkInfo( uint8_t networkItem, String &ssid, uint8_t &encryptionType, int32_t & RSSI, uint8_t* & BSSID , int32_t &channel);
To see how to use the WiFiScan , take a look at the WiFiScan.ino example available.
/*H******************************************************* WiFiAccessPoint.ino creates a WiFi access point and provides a web server on it. Steps: 1. Connect to the access point "yourAp" 2. Point your web browser to http://192.168.4.1/H to turn the LED on or http://192.168.4.1/L to turn it off OR Run raw TCP "GET /H" and "GET /L" on PuTTY terminal with 192.168.4.1 as IP address and 80 as port Created for arduino-esp32 on 04 July, 2018 by Elochukwu Ifediora (fedy0) ********************************************************/ #include <WiFi.h> #include <WiFiClient.h> #include <WiFiAP.h> //************************* DEFINES ************************************ #define BAUD 9600 #define LED_BUILTIN 2 //************************* PROTOTYPES ************************************ //************************* VARIABLES ************************************ WiFiServer server( 80 ); // SET GPIO PIN WHERE YOU CONNECTED TEST LED OR COMMENT THIS LINE OUT IF YOUR DEV BOARD HAS BUILT-IN LED // SET THESE TO YOUR DESIRED CREDENTIALS. const char *ssid = "yourAP"; const char *password = "yourPassword"; int value = 0; /*F******************************************************************** * **********************************************************************/ void setup() { pinMode( LED_BUILTIN, OUTPUT ); Serial.begin( BAUD ); Serial.println(); Serial.println( "Configuring access point..."); // CAN REMOVE PASSWORD PARAMETER IF YOU WANT AP TO BE OPEN WiFi.softAP( ssid, password ); IPAddress myIP = WiFi.softAPIP(); Serial.print( "AP IP address: " ); Serial.println( myIP ); server.begin(); Serial.println( "Server started" ); } /*F******************************************************************** * **********************************************************************/ void loop() { WiFiClient client = server.available(); // listen for incoming clients if( client ) { Serial.println( "New Client."); // IF YOU GET A CLIENT, String currentLine = ""; // PRINT MESSAGE OUT SERIAL PORT // MAKE A STRING TO HOLD INCOMING DATA FROM CLIENT while( client.connected() ) { // loop while the client's connected if( client.available() ) char c = client.read(); // READ A BYTE, THEN Serial.write( c ); // PRINT IT OUT SERIAL MONITOR if( c == '\n') { // BYTE IS A NEWLINE CHARACTER // IF 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: println( "HTTP/1.1 200 OK" ); client.println( "Content-type:text/html" ); client.println(); // CONTENT OF HTTP RESPONSE FOLLOWS HEADER: client.print( "Click <a href= \"/H \">here</a> turn on LED.<br>"); client.print( "Click <a href= \"/L \">here</a> to turn OFF the LED.<br>"); client.println();// HTTP RESPONSE ENDS WITH BLANK LINE: break; // BREAK OUT OF WHILE LOOP: } else { // if you got a newline, then clear currentLine: currentLine = ""; } } else if( c != '\r') { // GOT ANYTHING ELSE BUT A CARRIAGE RETURN CHARACTER, currentLine += c; // ADD IT TO THE END OF THE CURRENTlINE } // CHECK TO SEE IF CLIENT REQUEST WAS "GET /H" OR "GET /L": if( currentLine.endsWith( "GET /H")) { digitalWrite( LED_BUILTIN, HIGH); // GET /H TURNS LED ON } if( currentLine.endsWith( "GET /L")) { digitalWrite( LED_BUILTIN, LOW); // GET /L TURNS LED OFF } } } client.stop(); // CLOSE CONNECTION: Serial.println( "Client Disconnected."); } }
/*H******************************************************* * This sketch sends data via HTTP GET requests to data.sparkfun.com service. * You need to get streamId and privateKey at data.sparkfun.com and paste them * below. Or just customize this script to talk to other HTTP servers. ********************************************************/ #include <WiFi.h> //************************* DEFINES ************************************ typedef unsigned long ulong; //************************* PROTOTYPES ************************************ //************************* VARIABLES ************************************ const char *ssid = "your-ssid"; const char *password = "your-password"; const char *host = "data.sparkfun.com"; const char *streamId = "...................."; const char *privateKey = "...................."; /*F******************************************************************** * **********************************************************************/ void setup() { Serial.begin( BAUD ); delay( 10 ); Serial.println(); Serial.println(); Serial.print( "Connecting to " ); Serial.println( ssid ); WiFi.begin( ssid, password ); // START BY CONNECTING TO A WiFi NETWORK while( WiFi.status() != WL_CONNECTED) { delay( 500 ); Serial.print( "." ); } Serial.println( "" ); Serial.println( "WiFi connected"); Serial.println( "IP address: "); Serial.println( WiFi.localIP()); } /*F******************************************************************** * **********************************************************************/ void loop() { delay( 5000 ); ++value; Serial.print( "connecting to "); Serial.println( host ); WiFiClient client; // USE WiFiClient CLASS TO CREATE TCP CONNECTIONS const int httpPort = 80; if( !client.connect( host, httpPort)) { // CLIENT CONNECT FAILED??? Serial.println( "connection failed"); return; } String url = "/input/"; // CREATE URI FOR REQUEST url += streamId; url += "?private_key="; url += privateKey; url += "&value="; url += value; Serial.print( "Requesting URL: "); Serial.println( url ); // SEND REQUEST TO SERVER client.print( String( "GET ") + url + " HTTP/1.1 \r\n" + "Host: " + host " "+ " \r\n" + "Connection: close \r\n\r\n"); ulong timeout = millis(); while( client.available() == 0) { if( millis() - timeout > 5000 ) { Serial.println( ">>> Client Timeout !"); client.stop(); return; } } while( client.available() ) { // READ ALL LINES OF REPLY FROM SERVER AND PRINT TO SERIAL String line = client.readStringUntil( '\r'); Serial.print( line ); } Serial.println(); Serial.println( "closing connection"); }