断电后重新连接到Wifi并使用wifiManager和SPIFFS上传到somethingSpeak

时间:2019-03-29 02:04:50

标签: macos arduino-ide wifimanager arduino-esp8266 spiffs

我有一个ESP8266草图,允许用户在打开设备电源(连接到Arduino UNO v3的ESP8266)时输入其ip地址和密码以及thingSpeak编写api。我正在使用附件代码,这些代码使用Arduino IDE发送到设备。上载到ESP8266时,我使用Flash大小:512K(128K SPIFFS),因为代码中包含SPIFFS,并且已挂载FS,并且自定义参数被保存到配置文件中。无论如何,串行打印机都说是。
输入并保存ip地址和密码以及api.thingspeak.com和write api后,ESP8266将重新启动并连接,并开始将两个传感器读数上传到ThingSpeak。这很棒!! 但是,我希望自己的项目能够自给自足(电池和太阳能充电器),因此我试图尽可能减少用电量。 Arduino上的代码每小时都会打开ESP8266。当池由于蒸发而缓慢下降时,以及池充满时每两分钟。
问题是当我切断ESP8266的电源并重新启动时,什么也没发生。 ESP8266上的蓝灯闪烁,但未连接到wifi并连接到somethingSpeak并上传传感器读数。什么都没发生。 所以我的问题是: 如何做的是在(void)循环中连接到wifi,并获取存储在SPIFFS中的信息,以连接到ThingSpeak并上传到我的write API。我不明白为什么无法将信息存储在SPIFFS中。 另外我也不太确定如何使用WiFi重置针13。

这是我的代码。

#include <FS.h>

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>

//NEW STUFF START

char apiKey[20]="";
WiFiClient client;

char defaultHost[100] = "api.thingspeak.com";  //Thing Speak IP address (sometime the web address causes issues with ESP's :/
    long itt = 500;
    long itt2 = 500;

const byte wifiResetPin = 13;
int interruptPinDebounce = 0;
long debouncing_time = 1000;
volatile unsigned long wifiResetLastMillis = 0;


bool shouldSaveConfig = false;

void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;}

  void handleWifiReset(){
    if(millis()<wifiResetLastMillis){
      wifiResetLastMillis = millis();
    }
    if((millis() - wifiResetLastMillis)>= debouncing_time){
      Serial.println("Clearing WiFi data resetting");
      WiFiManager wifiManager;
      wifiManager.resetSettings();
      SPIFFS.format();
      ESP.reset();
      delay(1000);
    }
    wifiResetLastMillis = millis();
  }

void setup() {
  WiFiManager wifiManager;
    // put your setup code here, to run once:
    Serial.begin(115200);
    pinMode(wifiResetPin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(wifiResetPin), handleWifiReset,FALLING);

    //NEW STUFF START
    //clean FS, for testing
  //SPIFFS.format();

  //read configuration from FS json
  Serial.println("mounting FS...");

  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/config.json")) {
      //file exists, reading and loading
      Serial.println("reading config file");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile) {
        Serial.println("opened config file");
        size_t size = configFile.size();
        // Allocate a buffer to store contents of the file.
        std::unique_ptr<char[]> buf(new char[size]);

        configFile.readBytes(buf.get(), size);
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject(buf.get());
        json.printTo(Serial);
        if (json.success()) {
          Serial.println("\nparsed json");
          strcpy(defaultHost, json["defaultHost"]);
          strcpy(apiKey, json["apiKey"]);
        } else {
          Serial.println("failed to load json config");
        }
      }
    }
  } else {
    Serial.println("failed to mount FS");
  }
  WiFiManagerParameter customHostServer("defaultHost", "Host Server", defaultHost, 100);
  WiFiManagerParameter customAPIKey("apiKey", "ThingSpeakWriteAPI", apiKey, 20);
//END NEW STUFF
    //WiFiManager
    //Local intialization. Once its business is done, there is no need to keep it around
   //WiFiManager wifiManager;

    //NEW STUFF START 
    wifiManager.setSaveConfigCallback(saveConfigCallback);
    wifiManager.addParameter(&customHostServer);
    wifiManager.addParameter(&customAPIKey);
     //END NEW STUFF
    //reset saved settings
  //wifiManager.resetSettings();

    //set custom ip for portal
    //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0));

    //fetches ssid and pass from eeprom and tries to connect
    //if it does not connect it starts an access point with the specified name
    //here  "AutoConnectAP"
    //and goes into a blocking loop awaiting configuration
    wifiManager.autoConnect("AutoConnectAP");
    Serial.println("Connected");
  //NEW STUFF START
  strcpy(defaultHost, customHostServer.getValue());
  strcpy(apiKey, customAPIKey.getValue());
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["defaultHost"] = defaultHost;
    json["apiKey"] = apiKey;
    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }
    json.printTo(Serial);
    json.printTo(configFile);
    configFile.close();
    //end save
  }
  Serial.println("local ip");
  Serial.println(WiFi.localIP());
  //END NEW STUFF
    //or use this for auto generated name ESP + ChipID
    //wifiManager.autoConnect();
pinMode(2,INPUT);
pinMode(1,INPUT);
    Serial.println("WriteApi");
    Serial.println(apiKey);
    //if you get here you have connected to the WiFi
    Serial.println("connected...yeey :)");
     //save the custom parameters to FS
     strcpy(defaultHost,customHostServer.getValue());
  strcpy(apiKey,customAPIKey.getValue());
}
//callback notifying us of the need to save config
void loop() {
  delay(5000);

//THIS IS NEW CODE
    WiFiManager wifiManager;
    wifiManager.autoConnect("AutoConnectAP");
    Serial.println("Connected");

char defaultHost[100] = "api.thingspeak.com";
  pinMode(2,INPUT);
  pinMode(1,INPUT);

  const int waterInPin = 2;  // Analog input pin that the potentiometer is attached to
    const int BatteryInPin = 1;  // Analog input pin that the potentiometer is attached to
    int waterSensorInValue;//reading our water lever sensor
int waterSensorOutValue;//conversion of water sensor value
int BatterySensorInValue;//reading our water lever sensor
int BatterySensorOutValue;//conversion of water sensor value
    // put your main code here, to run repeatedly:
    waterSensorInValue = analogRead(waterInPin);
   BatterySensorInValue = analogRead(BatteryInPin);
  waterSensorOutValue = map(waterSensorInValue,0,1024,0,225);
  BatterySensorOutValue = map(BatterySensorInValue,0,1024,0,225);
 Serial.println("WaterOutValue = ");
  Serial.println(waterSensorOutValue );
  Serial.println("WaterInValue = ");
  Serial.println(waterSensorInValue );
  Serial.println("BatteryOutValue = ");
  Serial.println(BatterySensorOutValue );
  Serial.println("BatteryInValue = ");
  Serial.println(BatterySensorInValue);
    delay(18000);
    itt = waterSensorInValue;
    itt2 = BatterySensorInValue;
    if (client.connect(defaultHost,80))
    { // "184.106.153.149" or api.thingspeak.com
        itt++;  //Replace with a sensor reading or something useful

        String postStr = apiKey;
        postStr +="&field1=";
        postStr += String(itt);
        postStr +="&field2=";
        postStr += String(itt2);
        postStr += "\r\n\r\n\r\n";

        client.print("POST /update HTTP/1.1\n");
        client.print("Host: api.thingspeak.com\n");
        client.print("Connection: close\n");
        client.print("X-THINGSPEAKAPIKEY: "+String (apiKey)+"\n");
        client.print("Content-Type: application/x-www-form-urlencoded\n");
        client.print("Content-Length: ");
        client.print(postStr.length());
        client.print("\n\n\n");
        client.print(postStr);
        Serial.println("% send to Thingspeak");
    }
    client.stop();
    Serial.println("Waiting…");
    delay(55000);
}

请帮忙!

添加了新代码以在void循环中素描以连接到wifi,现在恢复供电后,ESP8266可以重新连接。现在,我要做的就是访问SPIFFS文件并获取ThingSpeak编写api,以便上传传感器数据。有人可以给我指出有关如何访问SPIFFS的示例/教程,或在此处为我编写示例。谢谢。我将尝试放置WiFiClient客户端;在我的循环代码中看看会发生什么。

0 个答案:

没有答案