将水位传感器信息获取到esp8266-01中,以上传到thingSpeak

时间:2019-04-15 23:19:55

标签: arduino esp8266 arduino-esp8266

我有一个项目,其中使用了Arduino UNO和esp8266-01。 Arduino用于收集水位高和水位低的传感器信息,然后将这些信息传输过来,以打开/关闭用于水阀的自锁继电器以填充我的游泳池。它还会关闭并在太阳能电池板上打开以为我的电池充电,也关闭并在esp8266上打开。
我希望每次esp8266开机时都可以连接到wifi,然后将水位传感器信息和电池水位传感器信息发送给thingSpeak。

在以下代码中,我使esp8266首次通电时尝试连接到本地wifi,但由于未提供IP和密码,因此它进入了接入点模式并打开了登录页面。我还向用户提供输入他们的somethingSpeak编写api的信息。该数据将保存到esp8266的eeprom中,以便将来自动连接并发送信息至thingSpeak。这很好。

我的问题是将水位传感器和电池水位的信息输入esp8266。我首先在Arduino上收集数据,然后让esp8266连接并使用SerialSoftware使用AT命令上传信息。但是要使AUTOCONNECT正常工作,我不得不重新编程esp8266,现在它不响应AT指令。我试图对ESP上的RX和TX引脚进行重新编程,但是当有水存在时,它只有两个读数,它的读数为1024,而无水为0。电池电量没有任何记录。我可以以某种方式使用TX和RX引脚作为模拟输入来执行此操作吗?还是可以使用Arduino上收集的信息(编号),并使用TX(arduino)和RX(ESP)将它们发送到ESP8266,以将它们发送到说话。我很茫然,需要帮助。

这是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);

}

正如我所说,几乎一切正常。 ESP8266在Arduino开启时打开。传感器启动并获取值。值会上传到ThingSpeak(只是一个有用的值。

任何想法,建议,示例,教程都将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:0)

我的建议是仅使用一个ESP32来完成所有这些工作。 它比使用两个微控制器要简单得多。 您可以使用ESP32读取和发送传感器数据,从而省去了通信两个不同的Micros的麻烦。