这段代码是用于 ESP8266 设备通过 WiFi 连接到指定的无线网络,并通过 HTTP 协议从指定的服务器更新程序/固件。该代码使用 ESP8266httpUpdate 库来实现程序/固件更新。其中包括定义 WiFi 连接信息、更新过程中的回调函数、更新结果的处理等。

/**
   httpUpdate.ino

    Created on: 27.11.2015

*/

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>

#include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h>

#ifndef APSSID
#define APSSID 'APSSID'
#define APPSK 'APPSK'
#endif

ESP8266WiFiMulti WiFiMulti;

void setup() {

  Serial.begin(115200);
  // Serial.setDebugOutput(false);

  Serial.println();

  ESPhttpUpdate.setClientTimeout(2000);  // default was 8000

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP(APSSID, APPSK);
}

void update_started() {
  Serial.println('CALLBACK:  HTTP update process started');
}

void update_finished() {
  Serial.println('CALLBACK:  HTTP update process finished');
}

void update_progress(int cur, int total) {
  Serial.printf('CALLBACK:  HTTP update process at %d of %d bytes...
', cur, total);
}

void update_error(int err) {
  Serial.printf('CALLBACK:  HTTP update fatal error code %d
', err);
}


void loop() {
  // wait for WiFi connection
  if ((WiFiMulti.run() == WL_CONNECTED)) {

    WiFiClient client;

    // The line below is optional. It can be used to blink the LED on the board during flashing
    // The LED will be on during download of one buffer of data from the network. The LED will
    // be off during writing that buffer to flash
    // On a good connection the LED should flash regularly. On a bad connection the LED will be
    // on much longer than it will be off. Other pins than LED_BUILTIN may be used. The second
    // value is used to put the LED on. If the LED is on with HIGH, that value should be passed
    ESPhttpUpdate.setLedPin(LED_BUILTIN, LOW);

    // Add optional callback notifiers
    ESPhttpUpdate.onStart(update_started);
    ESPhttpUpdate.onEnd(update_finished);
    ESPhttpUpdate.onProgress(update_progress);
    ESPhttpUpdate.onError(update_error);

    t_httpUpdate_return ret = ESPhttpUpdate.update(client, 'http://server/file.bin');
    // Or:
    // t_httpUpdate_return ret = ESPhttpUpdate.update(client, 'server', 80, 'file.bin');

    switch (ret) {
      case HTTP_UPDATE_FAILED: Serial.printf('HTTP_UPDATE_FAILD Error (%d): %s
', ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str()); break;

      case HTTP_UPDATE_NO_UPDATES: Serial.println('HTTP_UPDATE_NO_UPDATES'); break;

      case HTTP_UPDATE_OK: Serial.println('HTTP_UPDATE_OK'); break;
    }
  }
}

该代码首先包含了必要的库文件,并定义了 WiFi 连接信息。接着,它设置了更新过程中的回调函数,并在循环中尝试连接 WiFi。如果连接成功,代码将使用 ESPhttpUpdate 库从指定的服务器下载并更新固件。最后,根据更新结果,代码会打印相应的提示信息。

注意,该代码中使用了占位符,例如 'APSSID' 和 'APPSK',你需要将它们替换为你实际的 WiFi 网络名称和密码。同时,'http://server/file.bin' 也需要替换为你固件文件的实际地址。

ESP8266 WiFi 固件更新 - 使用 ESPhttpUpdate 库

原文地址: http://www.cveoy.top/t/topic/mGrh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录