1.使用VSCode,IDF版本4.2.2,利用HTTP方式进行ESP32空中升级的编程
2.复制esp-idf\examples\get-started里面的helloworld工程。
3.打开复制的工程,修改Makefile里的工程名称,同时添加如下代码段
EXTRA_COMPONENT_DIRS = $(IDF_PATH)/examples/common_components/protocol_examples_common
4.修改sdkconfig文件,对ESP32进行分区,该步骤也可通过idf.py menuconfig完成,添加一处代码
CONFIG_PARTITION_TABLE_TWO_OTA=y
5.将esp-idf\examples\system\ota\simple_ota_example中的server_certs复制到工程目录中
6.注意,修改main目录中的CMakeLists.txt中,增加
EMBED_TXTFILES ${project_dir}/server_certs/ca_cert.pem
7.编写如下代码段,便可进行OTA了,前提是先接入网络
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_ota_ops.h"
#include "esp_http_client.h"
#include "esp_https_ota.h"
#include "string.h"
#include "nvs.h"
#include "nvs_flash.h"
static const char *TAG = "simple_ota_example";
extern const uint8_t server_cert_pem_start[] asm("_binary_ca_cert_pem_start");
extern const uint8_t server_cert_pem_end[] asm("_binary_ca_cert_pem_end");
#define OTA_URL_SIZE 256
char OTA_URL[80];
esp_err_t _http_event_handler(esp_http_client_event_t *evt)
{
switch (evt->event_id)
{
case HTTP_EVENT_ERROR:
ESP_LOGD(TAG, "HTTP_事件_错误");
break;
case HTTP_EVENT_ON_CONNECTED:
ESP_LOGD(TAG, "HTTP_事件_ON_连接");
break;
case HTTP_EVENT_HEADER_SENT:
ESP_LOGD(TAG, "HTTP_事件_头_发送");
break;
case HTTP_EVENT_ON_HEADER:
ESP_LOGD(TAG, "HTTP_事件_ON_头, key=%s, value=%s", evt->header_key, evt->header_value);
break;
case HTTP_EVENT_ON_DATA:
ESP_LOGD(TAG, "HTTP_事件_ON_数据, len=%d", evt->data_len);
break;
case HTTP_EVENT_ON_FINISH:
ESP_LOGD(TAG, "HTTP_事件_ON_完成");
break;
case HTTP_EVENT_DISCONNECTED:
ESP_LOGD(TAG, "HTTP_事件_未连接");
break;
}
return ESP_OK;
}
void simple_ota_example_task(void *pvParameter)
{
ESP_LOGI(TAG, "开始 OTA 实例");
ESP_LOGI(TAG, "升级地址:%s",OTA_URL);
esp_http_client_config_t config = {
.url = OTA_URL,
.cert_pem = (char *)server_cert_pem_start,
.event_handler = _http_event_handler,
.keep_alive_enable = true,
};
esp_err_t ret = esp_https_ota(&config);
if (ret == ESP_OK)
{
esp_restart();
}
else
{
ESP_LOGE(TAG, "固件 升级 失败");
}
while (1)
{
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void ota_init(char * URL )
{
sprintf(OTA_URL,URL);
printf(OTA_URL);
printf("ota初始化-------------------------------------");
xTaskCreate(&simple_ota_example_task, "ota_example_task", 8192, NULL, 5, NULL);
}
8.调用ota_init("固件的地址"),完成OTA.