supla-device
Loading...
Searching...
No Matches
PzemV3.h
1// SPDX-FileCopyrightText: AC SOFTWARE SP. Z O.O.
2// SPDX-License-Identifier: GPL-2.0-or-later
3
4#ifndef SRC_SUPLA_SENSOR_PZEMV3_H_
5#define SRC_SUPLA_SENSOR_PZEMV3_H_
6
7#include <Arduino.h>
8// dependence: Arduino library for the Updated PZEM-004T v3.0 Power and Energy
9// meter https://github.com/mandulaj/PZEM-004T-v30
10#include <PZEM004Tv30.h>
11
12#define PZEM_0_DEFAULT_ADDR 0xF8
13
14#if defined(PZEM004_SOFTSERIAL)
15#include <SoftwareSerial.h>
16#endif
17#include <supla/time.h>
18
19#include "one_phase_electricity_meter.h"
20
21namespace Supla {
22namespace Sensor {
23
25 public:
26#if defined(PZEM004_SOFTSERIAL)
27 PZEMv3(uint8_t pinRX1,
28 uint8_t pinTX1,
29 uint8_t pzem_addr = PZEM_0_DEFAULT_ADDR)
30 : pzem{PZEM004Tv30(pinRX1, pinTX1, pzem_addr)} {
31 }
32#endif
33
34#if defined(ESP32)
35 PZEMv3(HardwareSerial *serial,
36 uint8_t pinRx1,
37 uint8_t pinTx1,
38 uint8_t pzem_addr = PZEM_0_DEFAULT_ADDR)
39 : pzem{PZEM004Tv30(serial, pinRx1, pinTx1, pzem_addr)} {
40 }
41#else
42 explicit PZEMv3(HardwareSerial *serial,
43 uint8_t pzem_addr = PZEM_0_DEFAULT_ADDR)
44 : pzem{PZEM004Tv30(serial, pzem_addr)} {
45 }
46#endif
47
48 void onInit() {
49 lastReadTime = millis();
50 readValuesFromDevice();
51 updateChannelValues();
52 }
53
54 virtual void readValuesFromDevice() {
55 float current = pzem.current();
56 // If current reading is NAN, we assume that PZEM there is no valid
57 // communication with PZEM. Sensor shouldn't show any data
58 if (isnan(current)) {
59 resetReadParameters();
60 return;
61 }
62
63 float voltage = pzem.voltage();
64 float active = pzem.power();
65 float apparent = (voltage * current);
66 float reactive = 0;
67 if (apparent > active) {
68 reactive = sqrt(apparent * apparent - active * active);
69 } else {
70 reactive = 0;
71 }
72
73 setVoltage(0, voltage * 100);
74 setCurrent(0, current * 1000);
75 setPowerActive(0, active * 100000);
76 setFwdActEnergy(0, pzem.energy() * 100000);
77 setFreq(pzem.frequency() * 100);
78 setPowerFactor(0, pzem.pf() * 1000);
79 setPowerApparent(0, apparent * 100000);
80 setPowerReactive(0, reactive * 100000);
81 }
82
83 void resetStorage() {
84 pzem.resetEnergy();
85 }
86
87 protected:
88 PZEM004Tv30 pzem;
89};
90
91}; // namespace Sensor
92}; // namespace Supla
93
94#endif // SRC_SUPLA_SENSOR_PZEMV3_H_
Definition one_phase_electricity_meter.h:11
Definition PzemV3.h:24
void onInit()
Third method called on element in SuplaDevice.begin()
Definition PzemV3.h:48