-
Notifications
You must be signed in to change notification settings - Fork 118
/
PZEMSoftwareSerial.ino
76 lines (61 loc) · 2.28 KB
/
PZEMSoftwareSerial.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
Copyright (c) 2021 Jakub Mandula
Example of using one PZEM module with Software Serial interface.
================================================================
If only RX and TX pins are passed to the constructor, software
serial interface will be used for communication with the module.
*/
#include <PZEM004Tv30.h>
#include <SoftwareSerial.h>
#if defined(ESP32)
#error "Software Serial is not supported on the ESP32"
#endif
/* Use software serial for the PZEM
* Pin 12 Rx (Connects to the Tx pin on the PZEM)
* Pin 13 Tx (Connects to the Rx pin on the PZEM)
*/
#if !defined(PZEM_RX_PIN) && !defined(PZEM_TX_PIN)
#define PZEM_RX_PIN 12
#define PZEM_TX_PIN 13
#endif
SoftwareSerial pzemSWSerial(PZEM_RX_PIN, PZEM_TX_PIN);
PZEM004Tv30 pzem(pzemSWSerial);
void setup() {
/* Debugging serial */
Serial.begin(115200);
}
void loop() {
Serial.print("Custom Address:");
Serial.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)){
Serial.println("Error reading voltage");
} else if (isnan(current)) {
Serial.println("Error reading current");
} else if (isnan(power)) {
Serial.println("Error reading power");
} else if (isnan(energy)) {
Serial.println("Error reading energy");
} else if (isnan(frequency)) {
Serial.println("Error reading frequency");
} else if (isnan(pf)) {
Serial.println("Error reading power factor");
} else {
// Print the values to the Serial console
Serial.print("Voltage: "); Serial.print(voltage); Serial.println("V");
Serial.print("Current: "); Serial.print(current); Serial.println("A");
Serial.print("Power: "); Serial.print(power); Serial.println("W");
Serial.print("Energy: "); Serial.print(energy,3); Serial.println("kWh");
Serial.print("Frequency: "); Serial.print(frequency, 1); Serial.println("Hz");
Serial.print("PF: "); Serial.println(pf);
}
Serial.println();
delay(2000);
}