2023-10-13 15:57:19 +00:00
|
|
|
#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->fram_address = fram_address;
|
2023-10-13 16:10:41 +00:00
|
|
|
this->adc_to_watts = adc_to_watts;
|
2023-10-13 15:57:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
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;
|
2023-10-13 16:10:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
float ESPMega_CT::adc_to_watts_builtin(uint16_t adc_value)
|
|
|
|
{
|
|
|
|
const float RATIO = 0.1;
|
|
|
|
const float BURDEN_RESISTANCE = 20;
|
|
|
|
const float VOLTAGE = 220;
|
|
|
|
const uint16_t ADC_RANGE_START = 500;
|
|
|
|
const uint16_t ADC_RANGE_END = 16000;
|
|
|
|
const float ADC_RANGE = 12;
|
|
|
|
float burden_voltage = (adc_value - ADC_RANGE_START) / (ADC_RANGE_END - ADC_RANGE_START) * ADC_RANGE;
|
|
|
|
float secondary_current = burden_voltage / BURDEN_RESISTANCE;
|
|
|
|
float primary_current = secondary_current / RATIO;
|
|
|
|
return primary_current * VOLTAGE;
|
2023-10-13 15:57:19 +00:00
|
|
|
}
|