0
votes

I have a project in which I have a water level sensor connected to my Arduino Uno r3. I have an ESP8266-01 module connected to my Arduino. Using AT commands I was able to upload the sensor result to ThinkSpeak. However I wanted to be able to log into other wifi channels so I put wifiManager.h, ESP8266WiFi.h, DNSServer.h, and ESP8266WebServer.h on my ESP8266 and everything worked fine. Since it couldn't connect because there was no IP and Password it opened up in AP mode and I connected to it from my computer and logged into it. I entered my IP Address and Password and hit SAVE and the ESP recycled and connected. I am now trying to upload the sensor data to thingSpeak but I think that AT commands don't work anymore since I get the error espData was not declared in this scope. Here is my code.

//this is new code I put onto ESP8266 and upload info from sensor to thinkSpeak using GPIO 2 As You can see I used wifiManager to connect to wifi and then read the sensor powered by the Arduino by the GPIO 2 port.

#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);

String apiKey2 = apiKey;
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(20000);
}

I will put other code on Arduino board not related to sensor or internet However the above code works great as long as it is connected to serial port and running directly after uploading code. If I unplug the Arduino from serial port on computer and then replug in nothing happens. I would think it should continue running the above code connecting to internet, reading sensor and sending info to thingSpeak but it doesn't. Any ideas why this is happening.

I replace the old code with new one that supposedly saves my thingSpeak write api to the SPIFFS. If I erase the setting and then upload with flash size set to 512k (128k SPIFFS) the FS mounts and the default Host and Api write key save to SPIFF and then the ESP8266 restarts connects to internet and goes to thingSpeak and update sensor readings. The problem remains that I want to turn off the ESP8266 to save energy but when I restart it only the (void) loop runs so even thought it connects to the wifi and maybe even to thingSpeak it does not update the sensor inputs. How do I get the information api write key from SPIFFS to the (void) loop part of my sketch so it will send sensor data to thingSpeak after shutting down. Or am I not connecting to ThingSpeak. Anyway this is a different question so I will repost with a more specific question and mark this answered.

1

1 Answers

0
votes

This answers a lot of the questions I had about the process of connecting to a different wifi and password with ESP8266 and Arduino uno and adding custom parameters. I still and having a few issues but will ask that in a separate post that hopefully someone can help me with.