官方历程参考esp\examples\wifi\fast_scan和scan
核心代码:
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());
esp_netif_t *sta_netif = esp_netif_create_default_wifi_sta();
assert(sta_netif);
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
uint16_t number = DEFAULT_SCAN_LIST_SIZE;
wifi_ap_record_t ap_info[DEFAULT_SCAN_LIST_SIZE];
uint16_t ap_count = 0;
memset(ap_info, 0, sizeof(ap_info));
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_start());
esp_wifi_scan_start(NULL, true);
ESP_ERROR_CHECK(esp_wifi_scan_get_ap_records(&number, ap_info));
ESP_ERROR_CHECK(esp_wifi_scan_get_ap_num(&ap_count));
ESP_LOGI(TAG, "Total APs scanned = %u", ap_count);
for (int i = 0; (i < DEFAULT_SCAN_LIST_SIZE) && (i < ap_count); i++) {
ESP_LOGI(TAG, "SSID \t\t%s", ap_info[i].ssid);
ESP_LOGI(TAG, "RSSI \t\t%d", ap_info[i].rssi);
print_auth_mode(ap_info[i].authmode);
if (ap_info[i].authmode != WIFI_AUTH_WEP) {
print_cipher_type(ap_info[i].pairwise_cipher, ap_info[i].group_cipher);
}
ESP_LOGI(TAG, "Channel \t\t%d\n", ap_info[i].primary);
}
}
SSID就是wifi的名称,
RSSI是wifi的信号强度,是一个负值,越大信号越强
这样在一个陌生的环境中,我们就可以用esp32去探测周围wifi 了.
扫描完之后,我们可以选择一个wifi去链接,并在回调函数里面调用事件
ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &event_handler, NULL, NULL));
在esp32成功进入wifi,得到ip后,我们这里使用 freertos的事件标志组,设置一下
(这里有一个坑,如果
调用ESP_ERROR_CHECK(esp_wifi_start());后直接开启socket任务,因为start函数并不是阻塞函数,会导致esp32并没有完全加入wifi,而开启socket,导致链接失败。
所以这边在回调中得到IP后,设置一个标志位,就可以解决这个问题了哈
后面
static void event_handler(void* arg, esp_event_base_t event_base,
int32_t event_id, void* event_data)
{
portBASE_TYPE xHigherPriorityTaskWoken;
if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
esp_wifi_connect();
} else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
esp_wifi_connect();
} else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
//xHigherPriorityTaskWoken = pdFALSE;
//xSemaphoreGiveFromISR( xMutex,xHigherPriorityTaskWoken);
// xSemaphoreGive( xMutex );
//xTaskCreate(tcp_client_task, "tcp_client", 8192, NULL, 5, NULL);
xEventGroupSetBits(
xCreatedEventGroup_one, // The event group being updated.
EventGroup_battry_recv
); // The bits being set.
}
}
然后在main这边等待一下这个标志位
然后开启tcp 的socket任务
uxBits = xEventGroupWaitBits(xCreatedEventGroup_one, /*事件组*/
EventGroup_battry_recv, /*等待的bit位*/
pdTRUE,
pdTRUE, /* ??? pdTRUE???? bit1? bit0 ????*/
5000); /* 超时时间100ms*/
if((uxBits & EventGroup_battry_recv) == EventGroup_battry_recv){//等待发送完
}else{
ESP_LOGI(TAG,"uart1 0x10 send timeout==============================================\r\n");
}
xTaskCreate(tcp_client_task, "tcp_client", 8192, NULL, 5, NULL);