0

I have a project in which I use an Arduino UNO and an esp8266-01. The Arduino is used to gather water high and water low sensor information and then transmit that information over to turn on/off a latching relay for a water valve to fill my pool. It also turns off and on a solar panel to charge my batteries and also turns off and on the esp8266.
I want to be able to connect to the wifi every time the esp8266 comes on and then send water level sensor information and battery level sensor information up to thingSpeak.

In the following code I have made it so that the first time the esp8266 is powered up it tries to connect to the local wifi but since no ip and password is provided it go to access point mode and opens a sign in page. I also provide the user to input their thingSpeak write api. This data is saved to the esp8266's eeprom so that in the future it will auto connect and send information to thingSpeak. This works fine.

My problem is getting the information from the water level sensor and the battery level into the esp8266. I was first gathering the data on the Arduino and then having the esp8266 connect and upload the information using AT commands using SerialSoftware. However to get the AUTOCONNECT to work I had to reprogram the esp8266 and now it doesn't respond to AT commands. I have tried to reprogram the RX and TX pins on the ESP but it only has two reading when there is water present it reads 1024 and no water is 0. Nothing in between. The battery level doesn't register anything. Can I do this using the TX and RX pins somehow as an analog input or can I take the information (numbers) gathered on the Arduino and had them off to the ESP8266 using the TX (arduino) and RX (ESP)to send them to ThingSpeak. I am at a loss and need help.

Here is the code on the ESP8266

#include <FS.h>
#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino
#include <EEPROM.h>
//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>         //https://github.com/tzapu/WiFiManager
#include <ArduinoJson.h>

//NEW STUFF START
char Password[36]="";
char apiKey[16]="";
WiFiClient client;
//eeprom new end
char defaultHost[100] = "";  //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();
  }

int addr = 0; 

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







  WiFiManagerParameter customAPIKey("apiKey", "ThingSpeakWriteAPI", apiKey, 16);
//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(&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(apiKey, customAPIKey.getValue());

  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["defaultHost"] = defaultHost;
    json["apiKey"] = apiKey;
    Serial.println("API");
    Serial.print(apiKey);
    String apiKey2 = String(apiKey);
    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }
json.printTo(configFile);
    json.printTo(Serial);
    delay(1000);
    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();


    //Serial.println("WriteApi");
    //Serial.println(apiKey);


    //if you get here you have connected to the WiFi
    //Serial.println("K)");
     //save the custom parameters to FS

  strcpy(apiKey,customAPIKey.getValue());
   EEPROM.begin(512);  //Initialize EEPROM

  // write appropriate byte of the EEPROM.
  // these values will remain there when the board is
  // turned off.

  EEPROM.write(addr, 'A');    //Write character A
  addr++;                      //Increment address
  EEPROM.write(addr, 'B');    //Write character A
  addr++;                      //Increment address
  EEPROM.write(addr, 'C');    //Write character A

  //Write string to eeprom
  String www = apiKey;
  for(int i=0;i<www.length();i++) //loop upto string lenght www.length() returns length of string
  {
    EEPROM.write(0x0F+i,www[i]); //Write one by one with starting address of 0x0F
  }
  EEPROM.commit();    //Store data to EEPROM


  //Read string from eeprom



}

//callback notifying us of the need to save config


void loop() {
 Serial.begin(115200);

 WiFiManager wifiManager;
if (WiFi.status() == WL_DISCONNECTED) {

 wifiManager.autoConnect("AutoConnectAP");}
 delay(5000);
 if (WiFi.status() == WL_CONNECTED) {  Serial.println("Connected");



WiFiClient client;
 long itt = 500;
    long itt2 = 500;
char defaultHost[100] ="api.thingspeak.com";

//HERE IS WHERE I CHANGE THE TX AND RX PIN FUNCTION
 pinMode(1, FUNCTION_3);
  pinMode(3, FUNCTION_3);
//THEN I ASSIGN THEM AS INPUT PINS 
 pinMode(1,INPUT);
 pinMode(3,INPUT);
//ASSIGN EACH PIN TO AN INTERGER
  const int waterInPin = 3;  // Analog input pin that the potentiometer is attached to
    const int BatteryInPin = 1;  // Analog input pin that the battery 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);
//ASSIGN THE INPUT VALUES TO UPLOAD LONGS    
    itt = waterSensorInValue;
    itt2 = BatterySensorInValue;
    EEPROM.begin(512);
    Serial.println(""); //Goto next line, as ESP sends some garbage when you reset it  
  Serial.print(char(EEPROM.read(addr)));    //Read from address 0x00
  addr++;                      //Increment address
  Serial.print(char(EEPROM.read(addr)));    //Read from address 0x01
  addr++;                      //Increment address
  Serial.println(char(EEPROM.read(addr)));    //Read from address 0x02

  //Read string from eeprom
  String www;   
  //Here we dont know how many bytes to read it is better practice to use some terminating character
  //Lets do it manually www.circuits4you.com  total length is 20 characters
  for(int i=0;i<16;i++) 
  {
    www = www + char(EEPROM.read(0x0F+i)); //Read one by one with starting address of 0x0F    
  }  

  Serial.print(www);  //Print the text on serial monitor




    if (client.connect(defaultHost,80))
    { // "184.106.153.149" or api.thingspeak.com
        itt++;  //Replace with a sensor reading or something useful
       //UPLOAD TO THINGSPEAK
        String postStr = www;
        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 (www)+"\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);

}

As I said almost everything works ok. The ESP8266 comes on when the Arduino turns it on. The sensor comes on and gets the value. A value is uploaded to ThingSpeak (just not a useful one.

Any Ideas, suggestions, examples, tutorials will be greatly appreciated. Thanks.

0

My suggestion is use only one ESP32 to do all this work. It´s much simpler and easier than using two micro-controllers. You can use the ESP32 to read and send the sensor data and save the trouble of communicating two different micros.

  • So I can't use a ESP8266-01 with just 8 pins, vcc, ground ,TX, RX, reset, CH-PD, gpio0, gpio2. I will look at the ESP32 but I have a lot of code in the arduino. I turn off/on the ESP8266, turn off on the solar panel to avoid overcharging, I switch to wall power to avoid the batteries going too low, I monitor the battery, I monitor the water level, I monitor a high water level and low monitor level. By turning things off and on I reduce power usage. – user1114881 Apr 17 at 14:55
  • You can use the ESP8266 if you don´t the pins are enough for your project or get the ESP32 if you need more pins. – Shark Apr 18 at 15:20
  • The code from the Arduino is probably compatible with the ESP. – Shark Apr 18 at 15:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.