以下是一個使用 ESP-IDF 來掃描 Wi-Fi 網路的程式範例。它將掃描周圍的 Wi-Fi 網路,並列印出它們的 SSID 及訊號強度(RSSI)。
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_wifi.h"
#include "esp_log.h"
#include "nvs_flash.h"
#define DEFAULT_SCAN_LIST_SIZE 20 // Define the number of APs to store
static const char *TAG = "wifi_scan";
void wifi_scan(void *pvParameters) {
// 1. Initialize Wi-Fi
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
// 2. Set Wi-Fi mode to STA (Station)
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_start());
// 3. Configure scan parameters
wifi_scan_config_t scan_config = {
.ssid = NULL,
.bssid = NULL,
.channel = 0,
.show_hidden = true
};
// 4. Start Wi-Fi scan
ESP_ERROR_CHECK(esp_wifi_scan_start(&scan_config, true));
// 5. Get scan results
uint16_t number = DEFAULT_SCAN_LIST_SIZE;
wifi_ap_record_t ap_info[DEFAULT_SCAN_LIST_SIZE];
ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&number, ap_info));
// 6. Get number of scanned networks
uint16_t ap_count = 0;
ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&ap_count));
ESP_LOGI(TAG, "Total APs found: %u", ap_count);
// 7. Print all SSIDs and RSSI (signal strength)
for (int i = 0; i < ap_count; i++) {
ESP_LOGI(TAG, "SSID: %s, RSSI: %d", ap_info[i].ssid, ap_info[i].rssi);
}
// Stop the Wi-Fi module
ESP_ERROR_CHECK(esp_wifi_stop());
vTaskDelete(NULL); // Delete task
}
void app_main(void) {
// Initialize NVS
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
// Create Wi-Fi scan task
xTaskCreate(&wifi_scan, "wifi_scan", 4096, NULL, 5, NULL);
}