1. 背景:
ESP8266是一个非常简单易用功能且强大的模块,而且可以使用arduino IDE开发,但是,硬件和不同系统的排列组合实在是太多了,而且因为ESP8266耗电,对电脑usb接口的驱动能力,线损都非常敏感,另外保不齐还会产生一些ch340驱动兼容性问题,比如我的mac系统在自动升级到Mojave之后,使用wemos模块时就反复出现识别不出端口,或者系统崩溃重启的现象。在windows台式机上前面的usb端口不认,后端的usb端口终于可以识别了,但usb线拉长了操作起来也是十分不方便的。
终于在吃了不少ESP8266通过usb线烧录失败的苦头后,我把注意力转向了无线更新。这样除了避免usb烧录的各种坑,还有一个额外的好处:即使以后esp8266和外围电路焊接安装之后,也能继续调试并无线升级模块以更新功能。
2. 正题:
现在我给出OTA可使用的最简框架代码,只要第一次用usb线将它烧录到esp8266芯片内,然后断开重新上电,稍作等待,arduino->工具中就会发现这个无线端口:
无线端口
以后每次更新程序只要包括了这段代码,就可以一直无线更新程序。
/*********
by Ningh
adapted from Arduino IDE example: Examples > Arduino OTA > BasicOTA.ino
*********/
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
// Replace with your network credentials
const char* ssid = "your-ssid";
const char* password = "your-password";
void setup() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
delay(500);
ESP.restart();
}
// Hostname defaults to esp8266-[ChipID]
//ArduinoOTA.setHostname("WemosEXP");
ArduinoOTA.begin();
}
void loop() {
ArduinoOTA.handle();
}
3. 注意要点:
1.无线更新需要系统装载了python 2.7,这个mac系统自带,windows需要安装,注意不要忘记要注册环境变量。
2.程序需要采用非阻塞式运行,delay尽量减少甚至避免,如果delay太长可能会导致OTA没法响应。
3.如果找不到无线端口,在确保模块上电的前提下关闭arduinoIDE再重新打开,则可以发现(实测发现有的时候第一次发现无线端口可能长达30秒,不过之后就快了)
4. 实例:
OTA点亮一个LED,非阻塞模式
/*********
by Ningh
adapted from
Arduino IDE example: Examples > Arduino OTA > BasicOTA.ino
Arduino IDE example: Examples > ESP8266 > BlinkWithoutDelay.ino
*********/
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
// Replace with your network credentials
const char* ssid = "your-ssid";
const char* password = "your-password";
const int ESP_BUILTIN_LED = 2;
int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 1000;
void setup() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
delay(500);
ESP.restart();
}
// Hostname defaults to esp8266-[ChipID]
//ArduinoOTA.setHostname("WemosEXP");
ArduinoOTA.begin();
pinMode(ESP_BUILTIN_LED, OUTPUT);
}
void loop() {
ArduinoOTA.handle();
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
if (ledState == LOW) {
ledState = HIGH; // Note that this switches the LED *off*
} else {
ledState = LOW; // Note that this switches the LED *on*
}
digitalWrite(ESP_BUILTIN_LED, ledState);
}
}