olehs / PZEM004T

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

stm32 bluepill hardware serial example not working #76

Open binarymaker opened 3 years ago

binarymaker commented 3 years ago

PZEMHardSerial Example not working. Some issues in PZEM constructor and Serial.begin() in the library. In stm32 library hardware configuration works after setup function invoke.

Please refer attached my workout example.

#include <PZEM004Tv30.h>

#if !defined(PZEM_SERIAL)
#define PZEM_SERIAL Serial2
#endif

PZEM004Tv30 *pzem;

void setup() {
    // Debugging Serial port
    Serial1.begin(115200);
    pzem = new PZEM004Tv30(PZEM_SERIAL);

    // Uncomment in order to reset the internal energy counter
    // pzem.resetEnergy()
}

void loop() {
    // Print the custom address of the PZEM
    Serial1.print("Custom Address:");
    Serial1.println(pzem->readAddress(), HEX);

    // Read the data from the sensor
    float voltage = pzem->voltage();
    float current = pzem->current();
    float power = pzem->power();
    float energy = pzem->energy();
    float frequency = pzem->frequency();
    float pf = pzem->pf();

    // Check if the data is valid
    if(isnan(voltage)){
        Serial1.println("Error reading voltage");
    } else if (isnan(current)) {
        Serial1.println("Error reading current");
    } else if (isnan(power)) {
        Serial1.println("Error reading power");
    } else if (isnan(energy)) {
        Serial1.println("Error reading energy");
    } else if (isnan(frequency)) {
        Serial1.println("Error reading frequency");
    } else if (isnan(pf)) {
        Serial1.println("Error reading power factor");
    } else {

        // Print the values to the Serial console
        Serial1.print("Voltage: ");      Serial1.print(voltage);      Serial1.println("V");
        Serial1.print("Current: ");      Serial1.print(current);      Serial1.println("A");
        Serial1.print("Power: ");        Serial1.print(power);        Serial1.println("W");
        Serial1.print("Energy: ");       Serial1.print(energy,3);     Serial1.println("kWh");
        Serial1.print("Frequency: ");    Serial1.print(frequency, 1); Serial1.println("Hz");
        Serial1.print("PF: ");           Serial1.println(pf);

    }

    Serial1.println();
    delay(2000);
}
vortigont commented 2 years ago

Looks like this is a wrong lib :) you might be talking about this one