OTA作为ESP8266的常用固件更新方法,在产品需要更新固件时候是非常重要的,在这里演示通过HTTP服务器更新固件的方法。
硬件我们本次使用零知-ESP8266;
软件使用零知开发工具,自带示例:
(1)先在零知开发工具中打开httpUpdate示例,或者复制下面的代码到零知开发工具中:
/**
httpUpdate.ino
Created on: 27.11.2015
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266httpUpdate.h>
#define USE_SERIAL Serial
#ifndef APSSID
#define APSSID "ssid"
#define APPSK "passwd"
#endif
ESP8266WiFiMulti WiFiMulti;
void setup() {
USE_SERIAL.begin(115200);
USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
for (uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(APSSID, APPSK);
}
void loop() {
// wait for WiFi connection
if ((WiFiMulti.run() == WL_CONNECTED)) {
WiFiClient client;
// USE_SERIAL.println("connected to wifi.");
// 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);
t_httpUpdate_return ret = ESPhttpUpdate.update(client, "http://192.168.0.111:8080/blink.bin");
// Or:
// t_httpUpdate_return ret = ESPhttpUpdate.update(client, "127.0.0.1", 8080, "blink.bin");
switch (ret) {
case HTTP_UPDATE_FAILED:
USE_SERIAL.printf("HTTP_UPDATE_FAILD Error (%d): %s\n", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
break;
case HTTP_UPDATE_NO_UPDATES:
USE_SERIAL.println("HTTP_UPDATE_NO_UPDATES");
break;
case HTTP_UPDATE_OK:
USE_SERIAL.println("HTTP_UPDATE_OK");
break;
}
}
}
(2)验证上传代码到零知-esp8266开发板;
在服务器中放置好需要更新的固件,这里以本地http服务器做演示,先用
npm install http-server -g
安装好http-server,将你需要更新的固件放置到一个目录下,这里以E:\Download目录为例,然后在这个目录开启http-server:
http-server -c-1
可以看到,服务器启动信息:
我们打开零知开发工具中的调试窗口,可以看到如下信息:
这里需要注意的一点是,我们的服务器IP和这里ESP8266模块的IP应该在同一个局域网,如果不是的话上一步就会出错。我们现在根据提示按下复位按键,就可以开始更新了:
更新成功后,就可以看到我们板子已经是运行更新后的固件了。