1

I’m trying to build a feeder machine on a pig farm by using the Infrared photoelectric switch Sensor E18-D80NK to control relay then send notifications to line and mqtt broker when it’s working. I have been testing for 2 days, it’s working normal, but third day, it’s not responding then I just press reset so it’s working again. I’m wondering it may cause by board cause it happen only one of four boards that I tasted or may be my code cause I was confused why output to line send “connected” so many times it’s should sent only one time when connected to wifi, so I’m not sure pls help.

Question

  1. Why board not responding after working normal for a while.
  2. Why out output to line send "connected" more than one cause I put in void setup()

Pictures

Last line output since working

All code

extra library line notification library

#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <TridentTD_LineNotify.h>

const char* ssid = "Artnaseaw-2.4G";
const char* password =  "0812667120";
const char* mqttUser = "****";
const char* mqttPassword = "****";

const char* mqttServer = "******";
const int mqttPort = *****;

const char* linetoken = "********";

long lastMsg = 0;
String DataString;
int lastL=0;    

WiFiClient espClient;
PubSubClient client(espClient);

const int ACTION = D8;

const int SENSOR = D2;

const char* host = "maker.ifttt.com";
const char *privateKey = "******";
const char *event = "*****";
String value1, value2;
String postData = "";
String MachineID="A01";

void setup() {
  Serial.begin(115200);
  pinMode(SENSOR, INPUT_PULLUP);
  pinMode(ACTION, OUTPUT);

  digitalWrite(SENSOR, LOW);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");

  client.setServer(mqttServer, mqttPort);

  client.setCallback(callback);

  while (!client.connected()) { 
    Serial.println("Connecting to MQTT...");

    if (client.connect("test", mqttUser, mqttPassword )) { 

      Serial.println("connected");

    } else {

      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);

    }
  }


  client.subscribe("command");  
  LINE.setToken(linetoken);
  LINE.notify("Connected");
  Serial.println("line send connected");
}

void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

  Serial.print("Message:");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  Serial.println("-----------------------");

}


void loop() {
  client.loop();

  delay(5000);

  int sensorValue = digitalRead(SENSOR);

     long now = millis();
  if (now - lastMsg > 60000) 
  {
    lastMsg = now;

    int sensorValue = digitalRead(SENSOR);
  if (sensorValue == LOW){
    Serial.println(" === Obstacle detected");
    Serial.print(" realy OFF ");
    digitalWrite(ACTION,LOW);
  } else {
     LINE.notify("send data to line ---working");
     Serial.println(" === All Clear");
     Serial.println(" relay ON ");
     digitalWrite(ACTION,HIGH);
     sendMessageToIFTTT();
     sendSensorToMQTT();
    }
  }
}
void sendSensorToMQTT(){
  char msg[100];
  int count = 1;
  DataString = "e18,location=test detest="+String(count);
  DataString.toCharArray(msg, 100);
  Serial.print("Publish message: ");
  Serial.println(msg);
  client.publish("e18", msg);   
}

void sendMessageToIFTTT(){

  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  String url = "/trigger/";
  url += event;
  url += "/with/key/";
  url += privateKey;

  value1 = "Worked";
  value2 = "1";

  genJSonObject();

  Serial.print("Requesting URL: ");
  Serial.println(url);
  Serial.println(postData);
  
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n");

  client.println("Content-Type: application/json");
  client.print("Content-Length: ");
  client.println(postData.length());
  client.println();
  client.println(postData);
  client.println("Connection: close\r\n\r\n");

  while (client.connected())
  {
    if (client.available())
    {
      String line = client.readStringUntil('\r');
      Serial.print(line);
    } else {
      // No data yet, wait a bit
      delay(50);
    };
  }
}


void genJSonObject()
{
  postData = "{";

  postData.concat("\"value1\":\"");
  postData.concat(value1);


  postData.concat("\",");
  postData.concat("\"value2\":\"");
  postData.concat(value2);

  postData.concat("\"}");
}
kati
  • 29
  • 3
  • 2
    What is the output from serial port of the board? – romkey Aug 23 '21 at 15:53
  • please edit your post and remove unused details and text to simplify your question and pay attention to focus on your main problem and explain more about it to help others answer your question. – nima Aug 24 '21 at 06:59
  • When you using String, try to declare it at where you need it, many of your variables don't need to be a global variable, e.g. `String DataString;` and many others. It reduce chances of running out of memory caused by head fragmentation, which might explain why your code no longer working after a few days. Read [this](https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/). – hcheung Aug 25 '21 at 15:32
  • 1
    When using array, you could do `sprintf(msg, "e18,location=test detest=%d", count);`, it simply your code and eliminate the need to create a String and then later convert to array. Read [sprintf](https://www.cplusplus.com/reference/cstdio/sprintf/?kw=sprintf). – hcheung Aug 25 '21 at 15:38
  • $5 says it's the usage of String throughout the program. Everytime you mutate a String, it's duplicated and Ardunio cannot cleanup the left over fragments. Sometimes it can re-use a heap hole, but the waste tends to build up and cause the MCU to run out of heap. Track heap usage when you report the other data and see if it dwindles before the MCU stops responding. Use printf() and char arrays instead of String- those don't leak memory. – dandavis Aug 26 '21 at 23:40

1 Answers1

0

Try to connect to another mqtt broker and see if it connects more than once in there too. If it happens the problem might be in the sketch. Otherwise, the cause may be with the IFTTT service.

Dharman
  • 30,962
  • 25
  • 85
  • 135
NeWi-SL
  • 127
  • 1
  • 6