@Stringyb92 , here you go. You might be able to put together better formulas than I have in the custom module - there are others out there.
- snippet from my device config
esphome:
name: mainsvoltagemeter
includes:
- zmpt101b_custom_sensor.h
sensor:
- platform: custom
lambda: |-
auto my_sensor = new ZMPT101BSensor();
App.register_component(my_sensor);
return {my_sensor};
sensors:
name: "Mains Voltage"
unit_of_measurement: V
accuracy_decimals: 0
state_class: "measurement"
- The custom module: zmpt101b_custom_sensor.h - this goes in the esphome folder
#include "esphome.h"
#include <Arduino.h>
#define VMAX 250
#define FREQUENCY 50
#define CALIBRATE_READ 130
#define CALIBRATE_ACTUAL 225
#define ZERO_VAC 788
class ZMPT101BSensor : public PollingComponent, public Sensor {
public:
// constructor
ZMPT101BSensor() : PollingComponent(1000) {}
float get_setup_priority() const override { return esphome::setup_priority::HARDWARE; }
void setup() override {
// This will be called by App.setup()
}
void update() override {
// This will be called every "update_interval" milliseconds.
uint32_t period = 1000000 / FREQUENCY;
uint32_t t_start = micros();
uint32_t Vsum = 0, measurements_count = 0;
int32_t Vnow;
while (micros() - t_start < period) {
Vnow = analogRead(A0) - ZERO_VAC;
Vsum += Vnow*Vnow;
measurements_count++;
}
float Vrms = sqrt(Vsum / measurements_count) / CALIBRATE_READ * CALIBRATE_ACTUAL;
publish_state(int(Vrms));
}
};