iot-firmware/src/espmega_iot_emon.cpp

91 lines
2.6 KiB
C++
Raw Normal View History

2023-11-15 09:52:52 +00:00
#include "espmega_iot_emon.hpp"
2023-11-15 09:52:52 +00:00
/**
* @brief Constructor for ESPMega_CT class.
*
* @param analog_pin The analog pin to read the current sensor from.
* @param adc_to_watts A function pointer to a function that converts ADC value to watts.
* @param fram_address The address of the FRAM to store energy data.
*/
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-11-15 09:52:52 +00:00
/**
* @brief Initializes the ESPMega_CT object.
*
* Reads the energy data from FRAM, sets the last conversion timestamp to current time, and calculates the current power.
*/
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));
}
2023-11-15 09:52:52 +00:00
/**
* @brief The main loop function of the ESPMega_CT object.
*
* Calculates the energy consumed since the last loop iteration, updates the current power, and writes the energy data to FRAM.
*/
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);
}
2023-11-15 09:52:52 +00:00
/**
* @brief Resets the energy data stored in FRAM and the energy variable.
*/
void ESPMega_CT::reset_energy()
{
this->energy = 0;
ESPMega_FRAM.write16(fram_address, 0);
}
2023-11-15 09:52:52 +00:00
/**
* @brief Returns the energy consumed since the object was initialized.
*
* @return The energy consumed since the object was initialized.
*/
long double ESPMega_CT::get_energy()
{
return this->energy;
}
2023-11-15 09:52:52 +00:00
/**
* @brief Returns the current power consumption.
*
* @return The current power consumption.
*/
float ESPMega_CT::get_power()
{
return this->power;
2023-10-13 16:10:41 +00:00
}
2023-11-15 09:52:52 +00:00
/**
* @brief A built-in function to convert ADC value to watts.
*
* @param adc_value The ADC value to convert to watts.
* @return The power in watts.
*/
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;
}