olehs / PZEM004T

Arduino communication library for Peacefair PZEM-004T Energy monitor
MIT License
225 stars 114 forks source link

Problems with Arduino Due #48

Closed colomblanc closed 5 years ago

colomblanc commented 5 years ago

Hi,

Thank you for making this project, it is really awesome and a great help.

I am trying to connect to a PZEM-004t using the Serial2 hardware port on my Arduino Due. It seems software serial is not available for Arduino Due so I tried to get it to work by adding the following line to the top of the .h file: #define PZEM004_NO_SWSERIAL

In my own document I include the following text:

#include <PZEM004T.h>
PZEM004T pzem(&Serial2);

With just the first line, the program is able to compile, upload and execute on my Arduino Due. When I add the second line, the program will compile, upload but not execute. I am puzzled. Is this an error in my code, an error in the library, or is the library not compatible with Arduino Due?

Best, Jonas

olehs commented 5 years ago

Hi, try this sketch

#include <PZEM004T.h>

PZEM004T* pzem;
IPAddress ip(192,168,1,1);

void setup() {
  while(!Serial) {
  }
  Serial.begin(9600);

  while(!Serial2) {
  }

  pzem = new PZEM004T(&Serial2);
  pzem->setAddress(ip);
}

void loop() {
  float v = pzem->voltage(ip);
  if (v < 0.0) v = 0.0;
  Serial.print(v);Serial.print("V; ");

  float i = pzem->current(ip);
  if(i >= 0.0){ Serial.print(i);Serial.print("A; "); }

  float p = pzem->power(ip);
  if(p >= 0.0){ Serial.print(p);Serial.print("W; "); }

  float e = pzem->energy(ip);
  if(e >= 0.0){ Serial.print(e);Serial.print("Wh; "); }

  Serial.println();
}
colomblanc commented 5 years ago

Beautiful - it works!

Would it be an idea to change the code in the examples to reflect the syntax above? Or will that create problems for other people?

I would suggest that you change the code in the header file so that it does not import softwareserial if the Arduino does not support it; I do not know if it is possible to detect for instance if the user has a Arduino Due somehow.

Best, Jonas

olehs commented 5 years ago

Done.