Scan Example

[中文]

Note

This document is automatically translated using AI. Please excuse any detailed errors. The official English version is still in progress.

Example Description

In Wi-Fi applications, scanning is used to obtain information about available wireless networks around, which is a key step in the connection process. Through scanning, the device can obtain information such as the SSID, BSSID, signal strength, channel, and security type of each access point (AP), thereby judging whether the target network exists and choosing the appropriate hotspot to connect based on this.

This function is commonly used in connection decisions, signal strength evaluation, network coverage verification, and network configuration debugging scenarios under station mode. At the same time, in multi-network environments, roaming, indoor positioning or multi-device collaboration applications, scanning also provides necessary data support.

This example shows how to scan for available wireless networks around in Wi-Fi station mode on ESP32, which is suitable for Wi-Fi network environment evaluation, channel interference analysis, and hotspot screening before connection.

Note

The scanning function can only be used in station mode or station+AP mixed mode.

Running Method

The complete code of the example can be found at scan example. The configuration instructions, build and burn process before running can be found in the README.md file in the example directory.

For custom configuration items and viewing default values, refer to the Macro Definition Description section in the document.

Header File Description

The header files used in this example cover basic modules such as FreeRTOS task management, Wi-Fi protocol stack, system event mechanism, log output, NVS non-volatile storage, and auxiliary function interface, and build the core functions of Wi-Fi initialization, scan control, event processing, and information output.

The header files are classified by function as follows:

  1. FreeRTOS Task Scheduling: Provides basic task scheduling, memory management, and event group synchronization mechanisms.

#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
  1. System Tools: Used for device MAC address acquisition, log printing, and non-volatile storage initialization.

#include "esp_log.h"
#include "nvs_flash.h"
  1. Wi-Fi and Event Mechanism: Includes Wi-Fi startup and connection configuration, event loop registration and processing functions.

#include "esp_wifi.h"
#include "esp_event.h"
  1. Auxiliary Functions and Standard Library: Provides basic string processing and regular expression interfaces.

#include "regex.h"

Note

The Wi-Fi scanning function does not involve network connection and communication, and only depends on the Wi-Fi driver layer.

Macro Definition Description

The macro definitions involved in this example are mainly used to control the number of scan results and the scan channel range during Wi-Fi scanning, to enhance flexibility and configuration adaptability.

The macro definitions are classified by function as follows:

  1. Scan List Size: Defines the size of the scan result array, indicating how many access points can be stored at most. The default is 10.

  • This macro is defined by the CONFIG_EXAMPLE_SCAN_LIST_SIZE configuration item, usually automatically generated based on the menuconfig setting, and saved in the sdkconfig file.

  • The maximum effective value of DEFAULT_SCAN_LIST_SIZE is 64. In actual applications, it is recommended to set the scan list size reasonably according to the needs to avoid occupying too much memory.

  1. Channel Bitmap: Used to control whether to enable the channel bitmap scanning method, which is off by default.

  • The channel bitmap is a data structure that uses “bits” to represent the status of multiple channels, commonly used in wireless communication systems, such as Wi-Fi, Bluetooth, Zigbee, etc., to indicate which channels are available, occupied, or disabled.

  • 1 indicates that the channel is available, and 0 indicates that the channel is not available (or disabled).

  • By defining CONFIG_EXAMPLE_USE_SCAN_CHANNEL_BITMAP, this feature can be enabled. Once enabled, the system will scan using the user’s preset channel list, rather than scanning the entire frequency band.

  • After the channel map is turned on, the USE_CHANNEL_BITMAP macro is set to 1 as an internal flag. In addition, after turning it on, you need to specify:

    • CHANNEL_LIST_SIZE: Set the size of the channel list, that is, define how many channels to scan, the default is 3.

    • Static array channel_list: Used to save the preset scan channel list, the default is {1, 6, 11}, that is, the commonly used 2.4GHz Wi-Fi channels.

  1. Channel Bitmap Conversion Interface: If the channel bitmap function is enabled, the array_2_channel_bitmap() function and its corresponding macro block will be automatically enabled.

Note

  • The above macro definitions will be automatically synchronized and updated after modifying menuconfig and rebuilding/compiling the example, no need to manually change the code.

  • You can directly edit these macros for quick testing, but configuring through menuconfig is more standardized and suitable for standard development processes.

Function Description

This example implements the ESP32’s active scanning of surrounding Wi-Fi networks through the wifi_scan() function, and completes channel control and classification output of scan result information through auxiliary functions array_2_channel_bitmap(), print_auth_mode() and print_cipher_type().

Among them, wifi_scan() is responsible for initializing the Wi-Fi driver, configuring scan parameters, initiating scan requests and outputting scan results, and is the core execution entry of the scan process; array_2_channel_bitmap() converts the user-defined channel array into a bitmap form when the channel bitmap function is enabled, for precise control of the scan channel; print_auth_mode() and print_cipher_type() are used to print the authentication method and encryption type of each access point, helping users identify the security attributes of different networks.

The functions work together to build a complete process of Wi-Fi scanning, achieving automatic processing of channel control, result extraction and parameter interpretation.

array_2_channel_bitmap()

Parameter Explanation

Input Parameter

Parameter Function

Parameter Description

channel_list[]

Channel Array

Used to store the list of channel numbers to be converted.

channel_list_size

Channel Array Length

The number of channels in the channel array.

scan_config

Pointer to Scan Configuration Structure

Points to the wifi_scan_config_t structure that needs to set the channel bitmap.

This function is used to convert the specified channel array into the channel bitmap in the Wi-Fi scan configuration structure, which is used to limit the range of channels to be scanned and optimize the scanning efficiency.

It should be noted that this function is only compiled and enabled when the macro USE_CHANNEL_BITMAP is defined.

wifi_scan()

The initialization of the scan mode mainly consists of two parts: initializing Wi-Fi and configuring it as station mode, and setting the scan mode.

The complete station mode initialization steps can be referred to in the station example document. This document will not repeat the repeated content, but only highlight the key implementations and differences in this example.

  1. Station Mode Configuration:

  • In the case of only using the scanning function without connecting to a specific access point, it is only necessary to perform the initialization stage, configuration stage and startup stage.

  • In the configuration stage, there is no need to configure connection parameters (such as SSID and password) through the wifi_config_t structure, nor is there a need to call esp_wifi_set_config() to apply these parameters.

  1. Initialize Result Cache Area: Define some variables for storing the AP information scanned later.

  • number: Represents the expected number of scan results, the initial value is scan list size DEFAULT_SCAN_LIST_SIZE.

  • ap_info[]: Used to store detailed information (such as SSID, signal strength, encryption type, etc.) of each AP scanned. The array type is wifi_ap_record_t, and the size is DEFAULT_SCAN_LIST_SIZE. For a complete list of included information, please refer to the Wi-Fi Library.

  • ap_count: Used to store the final number of APs scanned. This value will be assigned during the scan result processing stage.

  • Call memset() to clear all bytes of the ap_info array, ensuring that all fields in the structure have an initial value of 0, avoiding reading uninitialized garbage data.

  1. Choose Wi-Fi Scanning Method: This part executes two different scanning strategies depending on whether the USE_CHANNEL_BITMAP macro is defined:

  • If the channel bitmap is enabled:

    • Dynamically apply for and initialize a wifi_scan_config_t configuration structure.

    • Call the array_2_channel_bitmap() function to convert the specified channel list into a bitmap and fill it into the configuration, limiting the scan to these channels only.

    • Call esp_wifi_scan_start() to initiate a customized scan.

    • Release dynamically allocated memory after scanning to prevent memory leaks.

  • If the channel bitmap is not enabled:

    • Call esp_wifi_scan_start() to start a full channel scan with the default configuration (pass in NULL).

  • esp_wifi_scan_start() is used to start a Wi-Fi scan once, get information about the available access points around, support configuration parameters and blocking methods. The return value indicates the execution result. For more parameter descriptions, please refer to the Wi-Fi Library.

  1. Get relevant information and print:

  • Call esp_wifi_scan_get_ap_num() to get the total number of access points found in this scan, stored in ap_count. For more parameter descriptions, please refer to the Wi-Fi Library.

  • Call esp_wifi_scan_get_ap_records() to write up to number access point information into the ap_info array, and update number to the actual number obtained. For more parameter descriptions, please refer to the Wi-Fi Library.

  • Traverse ap_info, get and output the following information of each access point in turn:

    • SSID

    • RSSI

    • Authentication type (call print_auth_mode)

    • Encryption algorithm (call print_cipher_type)

Note

RSSI (Received Signal Strength Indicator) is used to indicate the signal strength received by the Wi-Fi module, in dBm. The closer the value is to 0, the stronger the signal (such as -40 dBm), and the smaller the value, the weaker the signal (such as -85 dBm). It is often used to evaluate the signal quality and connection stability of the access point.

Main Function Description

This function serves as the program entry function, used to complete the initialization of non-volatile storage (NVS), and start the Wi-Fi scanning function, providing a basic environment for subsequent acquisition of available wireless network information.

The steps implemented in the function are as follows:

  1. Initialize NVS

  2. Print startup information: Use log output Wi-Fi mode information.

  3. Start Wi-Fi initialization: Call wifi_scan() to complete network interface configuration, event registration, Wi-Fi parameter setting and driver startup, making ESP32 enter a working state that can perform wireless network scanning.