-
Notifications
You must be signed in to change notification settings - Fork 0
/
PZEM_SoftSerial.ino
330 lines (300 loc) · 9.55 KB
/
PZEM_SoftSerial.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
/*
* Use software serial for the PZEM
* Pin gpio2 Rx (Connects to the Tx pin on the PZEM)
* Pin gpio0 Tx (Connects to the Rx pin on the PZEM)
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <PZEM004Tv30.h>
#include "credentials.h" //this file keeps some private settings
WiFiClient wificlient;
WiFiClient glient; //Google client
//PZEM004Tv30 pzem(11, 12); //original config
//PZEM004Tv30 pzem(4, 5); //Rx,Tx,(D2,D1) on nodeMCU
//PZEM004Tv30 pzem(13, 15); //Rx,Tx,(D7,D8) another config
PZEM004Tv30 pzem(2, 0); //Rx,Tx,(gpio2,gpio0) on ESP-01
String tsStatus; //ThingSpeak, 255 char, null terminated
String status;
int error = 0; //0 no error; 1,2,4,8,16,32 -> errors for each parameter
float voltage, current, power, energy, frequency, pf;
float Vmax = 120.0;
float Vmin = 120.0;
float Pmax = 0.0;
int readAvg = 29; //nr of measurements averaged and sent to TS
int hour, minute, second, day, month, year;
//==============================================================================
// Functions
//==============================================================================
void wifiConnect(int n)
// "n" is the max number of tries to connect to SSID. If "n" reaches zero then
// wait for 15min and tries again for k (=100) cycles (100 * 15min ~ 25 hours)
{
WiFi.disconnect();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid,password);
int nn = n;
int k = 100; // [_] to put this at the beginning
while (k > 0)
{
while ((WiFi.status() != WL_CONNECTED) && (n > 0))
{
delay(1000);
Serial.print(n);Serial.print(" >");
//Serial.print(F(":"));
n--;
}//while
//either connected or n = 0
//if connected -> break
if (WiFi.status() == WL_CONNECTED)
{
Serial.print(F("\nWiFi connected to IP address: ")); //@
Serial.println(WiFi.localIP()); //@
break;//exit from outward while
//return;
}
if (n == 0) //not connected to wifi during n*1000ms
{
n = nn; //start over with initial n
k--;
if (k != 0)
{
delay(300000); // 5 min
}
else //-> k == 0
{
Serial.println(F("Restart"));
delay(50);//to allow the serial to finish
ESP.restart();
}
}
}//while
return;//this point is reached only from the above 'break'
}
String getTime()
{
//in the main prog is defined the client to access google as "glient"
Serial.println(F("connecting to google"));//@
//Serial.println(google); //@
if (!glient.connect(ghost, httpPort))
{
Serial.println(F("connection failed"));
return "google_fail";
}
// This will send the request to the server
glient.println("HEAD / HTTP/1.1");
glient.println("Host: www.google.com"); // "Host: www.google.com"
glient.println("Accept: */*");
glient.println("User-Agent: Mozilla/4.0 (compatible; esp8266 Arduino;)");
glient.println("Connection: close");
glient.println();
delay(500);
// Read all the characters of the reply from server and print them to Serial
String reply = String("");
while(glient.available())
{
char c = glient.read();
reply = reply + String(c);
}
//Serial.print(reply); //@
String d = reply.substring(reply.indexOf("Date: ")+11,reply.indexOf("Date: ")+23);
String t = reply.substring(reply.indexOf("Date: ")+23,reply.indexOf("Date: ")+35);
hour = t.substring(0, 2).toInt();
minute = t.substring(3, 5).toInt();
second = t.substring(6, 8).toInt();
day = d.substring(0, 2).toInt();
month = d.substring(3, 5).toInt();
year = d.substring(6, 8).toInt();
hour = hour + 16;//for summer is 16, for winter is 15
if (hour >= 24)
{
hour = hour % 24; //This is GMT - 4 -> Mtl hour
}
if(!glient.connected())
{
//Serial.println("disconnecting");
glient.stop();
}
Serial.println("connection closed"); //@
return t;
}
void setup()
{
Serial.begin(115200);
tsStatus = String("");
Serial.println(F("\nFilename: PZEM_SoftSerial.ino/30jun2020 "));
//WiFi.persistent(false);
//Wifi.persistent(false) is used for deep-sleep, to keep wifi param in ram
wifiConnect(60); //try for 60 seconds
glient.setTimeout(5000);
getTime();
}
void loop()
{
/*
the time is got first in setup(). The loop is parsed each two seconds so
I need a counter variable (or a time variable) to check the local time (millis)
to know when to ask again google for date&time.
I need also a procedure to sync on zero seconds.
The data is sent each minute.
*/
if ((WiFi.status() != WL_CONNECTED))
{
wifiConnect(60);
}
float Voltage = 0.0, Current = 0.0, Power = 0.0, Energy = 0.0, Frequency = 0.0, PF = 0.0;
for (int i = 0; i < readAvg; i++)
{
error = 0;
voltage = pzem.voltage();
if( !isnan(voltage) )
{
Serial.print("Voltage: "); Serial.print(voltage); Serial.println("V");
Voltage += voltage;
//check for Max and Min values
if (voltage > Vmax)
{
Vmax = voltage;
}
if (voltage < Vmin)
{
Vmin = voltage;
}
//send Vmax and Vmin as tsStatus
Serial.print("\tVmax = ");Serial.print(Vmax);Serial.println("V");
Serial.print("\tVmin = ");Serial.print(Vmin);Serial.println("V");
}
else
{
Serial.println(F("Error reading voltage"));
error = error + 1;
}
current = pzem.current();
if( !isnan(current) )
{
Serial.print("Current: "); Serial.print(current); Serial.println("A");
Current += current;
}
else
{
Serial.println(F("Error reading current"));
error = error + 2;
}
power = pzem.power();
if( !isnan(power) )
{
Serial.print("Power: "); Serial.print(power); Serial.println("W");
Power += power;
//check for Max value
if (power > Pmax)
{
Pmax = power;
}//--> to send Pmax as tsStatus
Serial.print("\tPmax = ");Serial.print(Pmax);Serial.println("W");
}
else
{
Serial.println(F("Error reading power"));
error = error + 4;
}
energy = pzem.energy();
if( !isnan(energy) )
{
Serial.print("Energy: "); Serial.print(energy,3); Serial.println("kWh");
Energy += energy;
}
else
{
Serial.println(F("Error reading energy"));
error = error + 8;
}
frequency = pzem.frequency();
if( !isnan(frequency) )
{
Serial.print("Frequency: "); Serial.print(frequency, 1); Serial.println("Hz");
Frequency += frequency;
}
else
{
Serial.println(F("Error reading frequency"));
error = error + 16;
}
pf = pzem.pf();
if( !isnan(pf) )
{
Serial.print("PF: "); Serial.println(pf);
PF += pf;
}
else
{
Serial.println(F("Error reading power factor"));
error = error + 32;
}
Serial.println();
if (error > 0)
{
Serial.print("--> Error: "); Serial.println(error);Serial.println();
}
delay(1950);
}//for
voltage = Voltage / readAvg;
current = Current / readAvg;
power = Power / readAvg;
energy = Energy / readAvg;
frequency = Frequency / readAvg;
pf = PF / readAvg;
status = "Error = " + String(error) + " / Pmax = " + String(Pmax) + " / Vmax = " + String(Vmax) + " / Vmin = " + String(Vmin);
tsStatus = String(status).c_str();
//Serial.println(status);
Serial.println(tsStatus);
//delay(2000);
transferData();
Vmax = 120.0;
Vmin = 120.0;
Pmax = 0.0;
}
//------------------------------------------------------------------------------
void transferData()
//transfer data to ThingSpeak
{
Serial.println(F("transferData()")); //@
String url = "/update?api_key=" + ThingSpeak_key +
"&field1=" + energy +
"&field2=" + power +
"&field3=" + voltage +
"&field4=" + current +
"&field5=" + frequency +
"&field6=" + pf +
"&status=" + tsStatus; //String(tsStatus).c_str();
//see the notes at the top of this file.
if (!wificlient.connect(ThingSpeak, 80))
{
Serial.println(F("connection to ThingSpeak failed"));
}
else
{
wificlient.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " +
ThingSpeak + "\r\n" + "Connection: keep-alive\r\n\r\n");
while (!wificlient.available())
{
//waiting...
}
delay(200);
}
if (gettsStatus()) Serial.println(F("Data transfer OK to ThingSpeak")); //@
}
boolean gettsStatus()
{
Serial.println(F("getStatus()")); //@
bool stat;
String _line;
_line = wificlient.readStringUntil('\n');
int separatorPosition = _line.indexOf("HTTP/1.1");
if (separatorPosition >= 0)
{
if (_line.substring(9, 12) == "200")
stat = true;
else
stat = false;
return stat;
}
}