Simple OTA upgrade for ESP8266

作者: shaneZhang 分类: IOT物联网 发布时间: 2020-08-02 22:15
#include <ESP8266WebServer.h>
#include <ESP8266HTTPUpdateServer.h>
#include<time.h>
#include <Ticker.h>
#include <ESP8266WiFi.h>
#include <WiFiManager.h>

byte board_led = 4;   //D1-mini板载灯脚,D4

Ticker slow_ticker;               //用于板载灯慢闪烁控制
ESP8266WebServer httpServer(81);  //用于web服务器
ESP8266HTTPUpdateServer httpUpdater;//用于代码OTA更新

// 建立WiFiManager对象
WiFiManager wifiManager;

void wifi_conn();

void setup() {
  Serial.begin(9600);

  pinMode(board_led, OUTPUT);  //设置板载灯脚为输出状态
  digitalWrite(board_led, LOW);   //点亮板载灯(低电平有效),开始连接WiFi    //预置WiFi名称和密码,这样模块在家和单位就都可以使用了

  wifi_conn();//连接WiFi
  //WiFi.printDiag(Serial);
}

void loop() {
  // Handle http server.
  httpServer.handleClient();
} 

void handleRoot() {
  String message = "<!DOCTYPE HTML>";
  message += "<html><head><meta charset=\"UTF-8\"><title>固件OTA升级</title>";
  message += "</head><body><div align=\"center\">";
  message += "<br><br><a href=\"/update\">点击这里</a> 进入OTA升级界面";
  message += "</div></div></body></html>";
  httpServer.send ( 200, "text/html", message );
} 

void handleNotFound() {
  //digitalWrite(board_led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += httpServer.uri();
  message += "\nMethod: ";
  message += (httpServer.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += httpServer.args();
  message += "\n";
  for (uint8_t i = 0; i < httpServer.args(); i++) {
    message += " " + httpServer.argName(i) + ": " + httpServer.arg(i) + "\n";
  }
  httpServer.send(404, "text/plain", message);
  //digitalWrite(board_led, 0);
} 

void led_blink(byte pin)
{ //指定pin脚改变其状态
  bool state = digitalRead(pin);  // 获得pin脚当前状态
  digitalWrite(pin, !state);      // 设置pin脚为反
} 

void wifi_conn() 
{ 

  if (wifiManager.autoConnect("CMCC_X11_ESP82"))
  {
    Serial.println("");
    Serial.print("ESP8266 Connected to ");
    Serial.println(WiFi.SSID());              // WiFi名称
    Serial.print("IP address:\t");
    Serial.println(WiFi.localIP());           // IP
  }
  
  httpServer.on("/", handleRoot);         //调用主页面
  httpServer.onNotFound(handleNotFound);  //出错调用

  // 开启 Web Update server.
  httpUpdater.setup(&httpServer);
  // 开启 HTTP server
  httpServer.begin();

  // 检查连接状态
  if (WiFi.status() == WL_CONNECTED)
  { 
    //如果WiFi连接成功
    slow_ticker.attach(0.8, led_blink, board_led);//WiFi连接正常,板载灯闪烁
  }
  else
  { //WiFi连接不成功
    Serial.println("wifi connect fail!");
    digitalWrite(board_led, HIGH); //WiFi连接失败,板载灯灭
  }
}

如果觉得我的文章对您有用,请随意打赏。如果有其他问题请联系博主QQ(909491009)或者下方留言!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注