initial energy monitoring implementation

This commit is contained in:
Siwat Sirichai 2023-10-13 22:57:19 +07:00
parent 61994fbbb2
commit 5757e93b57
2 changed files with 57 additions and 0 deletions

39
src/espmega_iot_emon.cpp Normal file
View File

@ -0,0 +1,39 @@
#include "espmega_iot_emon.hpp"
ESPMega_CT::ESPMega_CT(uint8_t analog_pin, float (*adc_to_watts)(uint16_t adc_value), uint32_t fram_address)
{
this->analog_pin = analog_pin;
this->adc_to_watts = adc_to_watts;
this->fram_address = fram_address;
}
void ESPMega_CT::begin()
{
this->last_conversion_timestamp = millis();
ESPMega_FRAM.read(fram_address, (uint8_t *)&this->energy, 16);
this->power = adc_to_watts(ESPMega_analogRead(this->analog_pin));
}
void ESPMega_CT::loop()
{
this->energy += (millis() - this->last_conversion_timestamp) / 3600000 * this->power;
this->power = adc_to_watts(ESPMega_analogRead(this->analog_pin));
this->last_conversion_timestamp = millis();
ESPMega_FRAM.write(fram_address, (uint8_t *)&this->energy, 16);
}
void ESPMega_CT::reset_energy()
{
this->energy = 0;
ESPMega_FRAM.write16(fram_address, 0);
}
long double ESPMega_CT::get_energy()
{
return this->energy;
}
float ESPMega_CT::get_power()
{
return this->power;
}

18
src/espmega_iot_emon.hpp Normal file
View File

@ -0,0 +1,18 @@
#pragma once
#include <ESPMegaPRO.h>
class ESPMega_CT {
public:
ESPMega_CT(uint8_t analog_pin,float(*adc_to_watts)(uint16_t adc_value), uint32_t fram_address);
void begin();
void loop();
float get_power();
long double get_energy();
void reset_energy();
private:
uint8_t analog_pin;
uint32_t fram_address;
unsigned long last_conversion_timestamp;
float power;
long double energy;
float (*adc_to_watts)(uint16_t adc_value);
};