arduino nano MQTT client with enc28j60

Hi all,
I'm developping a MQTT client based on arduino nano and ENC28J60 ethernet module (the goal is sending data to home assistant wit mqtt).

This is the code already used and working with an arduino mega and ENC28J60 ethernet module:

#include <PubSubClient.h>
#include <UIPEthernet.h>
#define DEBUG 1 // Debug output to serial console
#include "DHT.h"
#include <PZEM004T.h>
#define DHTPIN 8  
#define DHTTYPE DHT11 


DHT dht(DHTPIN, DHTTYPE);
PZEM004T pzem(2,3);  // (RX,TX) connect to TX,RX of PZEM
IPAddress i(10,10,1,1);
int sensorPin = A0; // Pin to which the sensor is connected to
unsigned long mytime = 0;
byte mac[] = {0x80, 0x7D, 0x3A, 0x69, 0x20, 0xC8 }; //physical mac address
byte ip[] = {192, 168, 0, 15 }; // ip in lan
const char* mqtt_server = "192.168.0.9";
const char* mqttUser = "user";
const char* mqttPassword = "pass";


char buf[4]; // Buffer to store the sensor value
int updateInterval = 30000; // Interval in milliseconds
EthernetClient espClient;
PubSubClient client(espClient);
 
void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("arduinoClientSuperior",mqttUser, mqttPassword)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}


void sensors() {
        int sensorValue = analogRead(sensorPin);
        float h = dht.readHumidity();
        float t = dht.readTemperature();
      
        client.publish("home-assistant/sensor01/brightness", itoa(sensorValue, buf, 10));
        client.publish("home-assistant/sensor02/temperature", String(t).c_str(), true);
        client.publish("home-assistant/sensor02/humidity", String(h).c_str(), true);


        float e = pzem.energy(i);                                          //energia     
        float p = pzem.power(i);                                           //potenza 
        float c = pzem.current(i);                                          //energia     
        float v = pzem.voltage(i);                                           //potenza
                     


        client.publish("home-assistant/sensor03/voltage", String(v).c_str(), true);
        client.publish("home-assistant/sensor03/energy", String(e).c_str(), true);
        client.publish("home-assistant/sensor03/power", String(p).c_str(), true);
        client.publish("home-assistant/sensor03/current", String(c).c_str(), true);
         
          #if DEBUG
            Serial.print("Sensor value: ");
            Serial.println(sensorValue);
            Serial.print("HuM value value: ");
            Serial.println(h);
            Serial.print("Temp value value: ");
            Serial.println(t);
            if(e >= 0.0){ Serial.print(e);Serial.print("Wh; "); }
            if(p >= 0.0){ Serial.print(p);Serial.print("W; "); }
            if(c >= 0.0){ Serial.print(c);Serial.print("A; "); }
            if(v >= 0.0){ Serial.print(v);Serial.print("V; "); }  
            Serial.println();
          #endif   
}
 
void setup()
{
  pzem.setAddress(i);
  Serial.begin(115200);
  delay(100);
  dht.begin();
  Ethernet.begin(mac,ip);
  client.setServer(mqtt_server, 1883);
}
 
void loop()
{
  if (!client.connected()) {    reconnect();  }
  client.loop();
  if (millis()-mytime>updateInterval)
      { mytime=millis(); 
        sensors();
      }
}

The sketch uses 29514byte (96%) and the memory used is 90%, so I have "low memory available, stability problems may occur"

How could I solve, using onother library? Using another ethernet board?
Many thanks

there is nothing in you sketch which would make it so large. do you have debug prints enabled in UIPEthernet and other libraries? do you use some very old IDE or AVR boards package?

EDIT:
compiled for Uno (without the DHT library):
Sketch uses 28070 bytes (87%) of program storage space. Maximum is 32256 bytes.
Global variables use 1710 bytes (83%) of dynamic memory, leaving 338 bytes for local variables. Maximum is 2048 bytes.

ok. with DHT it can be larger

try my EthernetENC library. it could be a little smaller

Thanks for your reply, now with this:

#include <EthernetENC.h>

#include <PubSubClient.h>
//#include <UIPEthernet.h>
#define DEBUG 0 // Debug output to serial console
#include "DHT.h"
#include <PZEM004T.h>


#define DHTPIN 8  
#define DHTTYPE DHT11 
DHT dht(DHTPIN, DHTTYPE);
PZEM004T pzem(2,3);  // (RX,TX) connect to TX,RX of PZEM
IPAddress i(10,10,1,1);
int sensorPin = A0; // Pin to which the sensor is connected to
unsigned long mytime = 0;
byte mac[] = {0x80, 0x7D, 0x3A, 0x69, 0x20, 0xC8 }; //physical mac address
byte ip[] = {192, 168, 0, 15 }; // ip in lan
const char* mqtt_server = "192.168.0.9";
const char* mqttUser = "";
const char* mqttPassword = "";

char buf[4]; // Buffer to store the sensor value
int updateInterval = 5000; // Interval in milliseconds
EthernetClient espClient;
PubSubClient client(espClient);

void reconnect() {
 // Loop until we're reconnected
 while (!client.connected()) {
   Serial.print("Attempting MQTT connection...");
   // Attempt to connect
   if (client.connect("arduinoClientSuperior",mqttUser, mqttPassword)) {
     Serial.println("connected");
   } else {
     Serial.print("failed, rc=");
     Serial.print(client.state());
     Serial.println(" try again in 5 seconds");
     // Wait 5 seconds before retrying
     delay(5000);
   }
 }
}

void sensors() {
       int sensorValue = analogRead(sensorPin);
       float h = dht.readHumidity();
       float t = dht.readTemperature();
     
       client.publish("home-assistant/sensor01/brightness", itoa(analogRead(sensorPin), buf, 10));
       client.publish("home-assistant/sensor02/temperature", String(t).c_str(), true);
       client.publish("home-assistant/sensor02/humidity", String(h).c_str(), true);

         #if DEBUG
           Serial.print("Sensor value: ");
           Serial.println(sensorValue);
           Serial.print("HuM value value: ");
           Serial.println(h);
           Serial.print("Temp value value: ");
           Serial.println(t);
           Serial.println();
         #endif   

       float e = pzem.energy(i);                                          //energia     
       float p = pzem.power(i);                                           //potenza 
       float c = pzem.current(i);                                          //energia     
       float v = pzem.voltage(i);                                           //potenza
                   
       client.publish("home-assistant/sensor03/voltage", String(v).c_str(), true);
       client.publish("home-assistant/sensor03/energy", String(e).c_str(), true);
       client.publish("home-assistant/sensor03/power", String(p).c_str(), true);
       client.publish("home-assistant/sensor03/current", String(c).c_str(), true);
   
         #if DEBUG
           if(e >= 0.0){ Serial.print(e);Serial.print("Wh; "); }
           if(p >= 0.0){ Serial.print(p);Serial.print("W; "); }
           if(c >= 0.0){ Serial.print(c);Serial.print("A; "); }
           if(v >= 0.0){ Serial.print(v);Serial.print("V; "); }  
           Serial.println();
         #endif   
            
}

void setup()
{
 pzem.setAddress(i);
 Serial.begin(115200);
 delay(100);
 dht.begin();
 Ethernet.begin(mac,ip);
 client.setServer(mqtt_server, 1883);
}

void loop()
{
 if (!client.connected()) {    reconnect();  }
 client.loop();
 if (millis()-mytime>updateInterval)
     { mytime=millis(); 
       sensors();
     }
}

Now The sketch uses 28298byte (92%) and the memory used is 74% and the message "low memory available, stability problems may occur" disappeared.
Everything works but if I add something I think the problem returns...

Could I do better?

use F macro for strings

I'm trying to disable the UDP support...

I already use a Static IP, but If I set UIP_CONF_UDP 0, on the consolle i see:
Attempting MQTT connection...failed, rc=-2 try again in 5 seconds

If I set UIP_CONF_UDP to 1, everything works again....

So if I disable UDP, the MQTT doesn't work!

Could I use F macro for this string?: String(t).c_str()

make mqtt_server an IPAddress. IP as string is evaluated with DNS and that uses UDP.

thanks, now :
Lo sketch usa 24336 byte (79%) dello spazio disponibile per i programmi. Il massimo è 30720 byte.
Le variabili globali usano 1392 byte (67%) di memoria dinamica

I think it's good

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.