发一个之前写的esp8266深度睡眠的http触发器
接上电池,用一个按钮把rst和gnd接上,按一下按钮就会自动开机发送请求,然后进入深度睡眠,可用于低功耗的物联网开关触发器(如需使用自动唤醒,还要将gpio16接到rst)#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266WebServer.h>
#include <arduino.h>
ESP8266WiFiMulti WiFiMulti;
ESP8266WebServer server(80);
const char* serverIndex = "<form method='POST' action='/update' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>";
ADC_MODE(ADC_VCC);
void setup() {
Serial.begin(115200);
Serial.print("\r\n\n");
pinMode(2,OUTPUT);
// WIFI
WiFi.mode(WIFI_STA);
WiFi.hostname("Sparkle");
WiFiMulti.addAP("wifi ssid", "wifi password");
int tryNum = 15;
Serial.print("Connect WiFi");
while (WiFiMulti.run() != WL_CONNECTED) {
digitalWrite(2,0);
delay(200);
digitalWrite(2,1);
delay(300);
Serial.print(".");
tryNum--;
if (tryNum == 0) {
// 1min
// ESP.deepSleep(60e6);
ESP.deepSleep(0);
}
}
Serial.print("\r\n");
digitalWrite(2,1);
Serial.print("IP address : ");
Serial.println(WiFi.localIP());
server.on("/", HTTP_GET, [](){
server.sendHeader("Connection", "close");
server.send(200, "text/html", serverIndex);
});
server.on("/update", HTTP_POST, [](){
server.sendHeader("Connection", "close");
server.send(200, "text/plain", (Update.hasError())?"FAIL":"OK");
ESP.restart();
},[](){
HTTPUpload& upload = server.upload();
if(upload.status == UPLOAD_FILE_START){
Serial.setDebugOutput(true);
Serial.printf("Update: %s\n", upload.filename.c_str());
uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
if(!Update.begin(maxSketchSpace)){
Update.printError(Serial);
}
} else if(upload.status == UPLOAD_FILE_WRITE){
if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
Update.printError(Serial);
}
} else if(upload.status == UPLOAD_FILE_END){
if(Update.end(true)){
Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
} else {
Update.printError(Serial);
}
Serial.setDebugOutput(false);
}
yield();
});
digitalWrite(2,0);
mainAction();
if (digitalRead(0)){
ESP.deepSleep(0);
} else {
server.begin();
}
}
void loop() {
server.handleClient();
delay(1);
}
String doGet(String url){
if ((WiFiMulti.run() == WL_CONNECTED)) {
HTTPClient http;
Serial.println(" begin...");
if (url.startsWith("https")) {
http.begin(url, "7a 9c f4 db 40 d3 62 5a 6e 21 bc 5c cc 66 c8 3e a1 45 59 38");
} else {
http.begin(url);
}
Serial.println(" GET...");
int httpCode = http.GET();
if (httpCode > 0) {
Serial.printf(" code: %d\n", httpCode);
if (httpCode == HTTP_CODE_OK) {
String payload = http.getString();
Serial.println(payload);
Serial.print("\r\n");
return payload;
}
} else {
Serial.printf(" GET... failed, error: %s\n",
http.errorToString(httpCode).c_str());
}
http.end();
return "";
}
}
void mainAction() {
// 发送请求
doGet("http://google.cn");
}
谢谢大神 分享
谢谢大神 分享 谢谢大神 分享
页:
[1]