You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

106 lines
3.0 KiB

#include <Arduino.h>
#include <HardwareSerial.h>
#include "WiFi.h"
#include "WiFiMulti.h"
#include "src/InfluxDB-Client-for-Arduino/src/InfluxDbClient.h"
#include "src/PZEM-004T-v30/PZEM004Tv30.h"
#include "config.h"
WiFiMulti WiFiMulti;
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_DB_NAME);
PZEM004Tv30 pzem(&Serial2);
// Data point
Point sensor("Solar_1");
void ConnectToWiFiMulti() {
WiFi.mode(WIFI_STA);
WiFiMulti.addAP(SSID, WiFiPassword);
Serial.println("Connecting Wifi...");
while (WiFiMulti.run() != WL_CONNECTED) {
delay(100);
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void ConnectToInflux() {
// Add constant tags - only once
sensor.addTag("device", "ESP32-Solar");
// Check server connection
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
}
void setup() {
Serial.begin(115200);
ConnectToWiFiMulti();
ConnectToInflux();
}
void loop() {
sensor.clearFields();
sensor.addField("wifi-rssi", WiFi.RSSI());
float voltage = pzem.voltage();
if(!isnan(voltage)){
sensor.addField("voltage", voltage);
Serial.print("Voltage: "); Serial.print(voltage); Serial.println("V");
} else {
Serial.println("Error reading voltage");
}
float current = pzem.current();
if(!isnan(current)){
sensor.addField("current", current);
Serial.print("Current: "); Serial.print(current); Serial.println("A");
} else {
Serial.println("Error reading current");
}
float power = pzem.power();
if(!isnan(power)){
sensor.addField("power", power);
Serial.print("Power: "); Serial.print(power); Serial.println("W");
} else {
Serial.println("Error reading power");
}
float energy = pzem.energy();
if(!isnan(energy)){
sensor.addField("energy", energy);
Serial.print("Energy: "); Serial.print(energy,3); Serial.println("kWh");
} else {
Serial.println("Error reading energy");
}
float frequency = pzem.frequency();
if(!isnan(frequency)){
sensor.addField("freq", frequency);
Serial.print("Frequency: "); Serial.print(frequency, 1); Serial.println("Hz");
} else {
Serial.println("Error reading frequency");
}
float pf = pzem.pf();
if(!isnan(pf)){
sensor.addField("power-factor", pf);
Serial.print("PF: "); Serial.println(pf);
} else {
Serial.println("Error reading power factor");
}
// If no Wifi signal, try to reconnect it
if ((WiFi.RSSI() == 0) && (WiFiMulti.run() != WL_CONNECTED))
Serial.println("Wifi connection lost");
// Write point
if (!client.writePoint(sensor)) {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}
//Wait 5s
Serial.println("Wait 5s");
delay(5000);
}