Hi all,
I have this simple sketch that reads a couple of sensors and send the data to a mqtt broker via enc28j60. The thing is that from time to time the enc28j60 lost connection and the only way to go back is by rebooting the Arduino.
As far as I got, the problem is related to low memory, so I reduced my use of globals as far as I can, which result in some improvement, but still having issues.
So, I’m looking for some help in a way to reduce even more the use of dynamic memory, if that is possible.
Any help is very appreciated.
Cheers.
#include <SPI.h>
#include <UIPEthernet.h>
#include <PubSubClient.h>
#include <EmonLib.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
// Update these with values suitable for your network.
const byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
const IPAddress ip(10, 102, 0, 6);
const IPAddress subnet(255, 255, 255, 192);
const IPAddress server(10, 9, 200, 238);
/*----------------------------------------
* ENERGIA
*/
EnergyMonitor emon1;
//Tensao da rede eletrica0
const int rede = 110;
//Pino do sensor SCT
const int pino_sct = 1;
const int burden_res = 77.7; //Burden resistor value in ohms
double Irms = 0;
/*------------------------------------------
* TEMPERATURA
*/
const int tempPin = 0;
int samples[8];
float tC = 0;
LiquidCrystal_I2C lcd(0x3f,2,1,0,4,5,6,7,3, POSITIVE);
EthernetClient ethClient;
PubSubClient mqttClient(ethClient);
void reconnect() {
// Loop until we're reconnected
while (!mqttClient.connected()) {
ethClient.stop();
Serial.print(F("Attempting MQTT connection..."));
// Attempt to connect
if (mqttClient.connect("arduinoClient", "someuser", "somepassword")) {
Serial.println(F("connected"));
} else {
Serial.print(F("failed, rc="));
Serial.print(mqttClient.state());
Serial.println(F(" try again in 30 seconds"));
// Wait 30 seconds before retrying
delay(30000);
}
}
}
void setup()
{
Serial.begin(9600);
lcd.begin (16,2);
emon1.current(pino_sct, 2000/burden_res);
Ethernet.begin(mac, ip, subnet);
// Allow the hardware to sort itself out
delay(1500);
mqttClient.setServer(server, 1883);
Serial.println(ip);
}
void loop()
{
if (!mqttClient.connected()) {
Serial.println(F("Connection Lost"));
reconnect();
}
Irms = emon1.calcIrms(1480);
float tCtemp = 0;
for(int i=0; i<1000; i++) {
tCtemp = analogRead(tempPin);
tC = tC + tCtemp;
}
tC = tC/1000;
tC = (tC * 0.475);
char msgBuffer[8];
mqttClient.publish("sensors/dtc01/Irms", dtostrf(Irms, 6, 3, msgBuffer));
mqttClient.publish("sensors/dtc01/Power", dtostrf(Irms*rede, 6, 3, msgBuffer));
mqttClient.publish("sensors/dtc01/Temperature", dtostrf(tC, 6, 3, msgBuffer));
lcd.setCursor(0,0);
lcd.print(Irms);
lcd.print(F(" A"));
lcd.setCursor(8,0);
lcd.print(Irms*rede);
lcd.print(F(" W"));
lcd.setCursor(0,1);
lcd.print(F("Temp: "));
lcd.print(tC);
lcd.print(F(" "));
lcd.print((char)223);
lcd.print(F("C"));
delay(1000);
mqttClient.loop();
}