Go Down

Topic: problema connessione MQTT con lettura analogica (Read 86 times) previous topic - next topic

Cencio

Salve a tutti

ho un problema di connessione del broker MQTT, al momento in cui inserisco la funzione "read_water_sensor" che esegue una lettura analogica sul pin A0 si disconnette, tenta la connessione ma senza risultato.
Senza la suddetta funzione va tutto regolarmente. Allego lo sketch.

Grazie in anticipo per l'aiuto
Davide

Code: [Select]
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
//#include <Bounce2.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

IPAddress staticIP(xxx, xxx, xxx, xxx); //ESP static ip
IPAddress gateway(xxx, xxx, xxx, xxx);
IPAddress subnet(255, 255, 255, 0);

const char* ssid =        "xxxxxxxxxx"; //SSID WIFI Access Point
const char* password =    "xxxxxxxxxx"; //Access Point Password
const char* mqtt_server = "xxxxxxxxxx"; //IP address MQTT server

Adafruit_BME280 bme;
WiFiClient espClient;
PubSubClient client(espClient);
long lastMsg = 0;
char msg[50];
int value = 0;

const char* inTopic_irriguo           = "openhab/nodo8/irriguo/command";
const char* switchTopic_temperature   = "openhab/nodo8/temperature/state";
const char* switchTopic_humidity      = "openhab/nodo8/humidity/state";
const char* switchTopic_pressure      = "openhab/nodo8/pressure/state";

const int irriguo         =  5;
const int BLINK           = 12;

const int soglia_critica = 700;
int sensorValue = analogRead(A0);
unsigned long previousMillis = 0;
const long interval = 60000;
String topicString = "";

//----------------------------FUNZIONI-----------------------------------------------------------

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.mode(WIFI_STA);
  WiFi.config(staticIP, gateway, subnet);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    for (int i = 0; i < 500; i++) {
      delay(1);
    }
    Serial.print(".");
  }
  digitalWrite(BLINK, LOW);
  delay(500);
  digitalWrite(BLINK, HIGH);
  delay(500);
  digitalWrite(BLINK, LOW);
  delay(500);
  digitalWrite(BLINK, HIGH);
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  topicString = topic;
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  if (topicString == "openhab/nodo8/irriguo/command") {
    if ((char)payload[1] == 'F')  {
      digitalWrite(irriguo, LOW);
    } else if ((char)payload[1] == 'N') {
      digitalWrite(irriguo, HIGH);
    }
  }
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("nodo_8_terrazza")) {
      Serial.println("connected");
      //Subscribe to incoming commands
      client.subscribe(inTopic_irriguo);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      for (int i = 0; i < 5000; i++) {
        delay(1);
      }
    }
  }
}

void getWeather() {

  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval) {
    float t = bme.readTemperature();
    float h = bme.readHumidity();
    float p = bme.readPressure() / 100.0F;
    if (isnan(h) || isnan(t) || isnan(p)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }
    previousMillis = currentMillis;
    Serial.println("DTH sensor read and transmitted");
    client.publish(switchTopic_temperature, String(t).c_str(), true);
    client.publish(switchTopic_humidity, String(h).c_str(), true);
    client.publish(switchTopic_pressure, String(p).c_str(), true);
  }
}

void read_water_sensor() {

  int sensorValue = analogRead(A0);
  if  ((sensorValue < soglia_critica)) {
    digitalWrite(irriguo, LOW);
  }
}

//--------------------------SETUP----------------------------------------------------
void setup() {

  ArduinoOTA.onStart([]() {
    Serial.end();
  });

  String line = "";

  pinMode(irriguo, OUTPUT);
  pinMode(BLINK,   OUTPUT);

  digitalWrite(BLINK, LOW);          // Blink to indicate setup
  delay(50);
  digitalWrite(BLINK, HIGH);
  delay(50);

  Serial.begin(115200);
  setup_wifi();                   // Connect to wifi

  Wire.begin(D3, D4);
  Wire.setClock(100000);
  Serial.println(F("BME280 test"));
  if (!bme.begin()) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    while (1);
  }

  client.setServer(mqtt_server, 1883); //connect to MQTT
  client.setCallback(callback);

  ArduinoOTA.setHostname("nodo8_terrazza");
  //ArduinoOTA.setPassword((const char *)"23753");
  ArduinoOTA.onStart([]() {
    Serial.println("Start");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  ArduinoOTA.begin();
  Serial.println("Ready");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

//-------------------------------LOOP-----------------------------------------------------
void loop() {
  ArduinoOTA.handle();

  if (!client.connected()) {
    reconnect();
  }
  if (WiFi.status() == WL_CONNECTED) {
    digitalWrite(BLINK, HIGH);
  }
  client.loop();
  getWeather();
  read_water_sensor();

}








Cencio

Ho risolto cosi':

Code: [Select]
void read_sensor_water() {
 if( millis() % 500 != 0 )
       return;
         
   int sensorValue = analogRead(A0);
   const int soglia_critica = 700;
  if  ((sensorValue < soglia_critica)){
    Serial.println(sensorValue);
    digitalWrite(irriguo, LOW);
    client.publish(switchTopic_irriguo_feedback, "OFF", true);
    }
  }



leggendo in giro, ho scoperto che la ESP non regge contemporaneamente la connessione wifi assieme a una serie di letture analogiche multiple vista la scarsa capacita' di calcolo.
Rallentando la lettura dovrei aver risolto

saluti
Davide

nid69ita

Grazie per aver condiviso la tua soluzione.  :)
my name is IGOR, not AIGOR

Go Up