#include <stdio.h>
#include <stdint.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "driver/adc.h"
#include "freertos/timers.h"
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <driver/adc.h>
#include "driver/ledc.h"
#include "driver/gpio.h"
#include "esp_spi_flash.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "sdkconfig.h"
#include "hal/ledc_types.h"
#define DC_RELAY_CONTACTOR 33
// D4 adc2 0
// D2 adc2 2
// D15 adc2 3
float read_adc(adc_channel_t channel)
{
int* raw_out;
uint32_t adc_value = adc2_get_raw(channel, ADC_WIDTH_BIT_12, &raw_out);
float voltage = adc_value * 3.3 / 4095;
printf("Voltage: %.2fV\n", voltage);
return voltage;
}
float read_current(adc_channel_t channel)
{
uint32_t raw_out;
uint32_t RawValue = adc2_get_raw(channel, ADC_WIDTH_BIT_12, &raw_out);
double Volt = RawValue * 3.3 / 4095;
float current = (Volt - 1.65) / 0.066;
printf("Current: %.2f\n", current);
return current;
}
float energy_consumed(time_t time)
{
float voltage_V = read_adc(ADC1_CHANNEL_0);
float current_A = read_current(ADC1_CHANNEL_6);
float energy_KWh = (voltage_V * current_A * time) / 1000;
printf("energy_KWh: %.2fKWh\n", energy_KWh);
return energy_KWh;
}
void app_main(void)
{
gpio_set_direction(DC_RELAY_CONTACTOR, GPIO_MODE_OUTPUT);
adc1_config_width(ADC_WIDTH_BIT_12);
adc1_config_channel_atten(ADC2_CHANNEL_0, ADC_ATTEN_DB_11);
adc1_config_channel_atten(ADC2_CHANNEL_2, ADC_ATTEN_DB_11);
adc1_config_channel_atten(ADC2_CHANNEL_3, ADC_ATTEN_DB_11);
time_t start_time;
time(&start_time);
int balance = 20;
while (balance)
{
unsigned long n = read_adc(ADC2_CHANNEL_1);
while ((n >= 621) && (n <= 1242))
{
n = read_adc(ADC2_CHANNEL_1);
gpio_set_level(DC_RELAY_CONTACTOR, 1);
time_t now;
time(&now);
printf("charging\n");
time_t time_passed = now - start_time;
printf("%lld\n", time_passed);
float energy = energy_consumed(time_passed);
printf("energy: %f\n", energy);
// oprn websocket over MQTT_Protocol
// balance = balance - energy_consume * charging_rate
}
printf("error");
gpio_set_level(DC_RELAY_CONTACTOR, 0);
}
}