/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2026 Arrive.
  * Author: D. Rice
  *
  * Version: 0.1
  *
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stm32g4xx_hal.h"
#include <stdint.h>
#include <string.h>

#define AVG_WINDOW 32

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
typedef struct
{
  uint32_t buffer[AVG_WINDOW];
  uint8_t index;
  uint32_t sum;
} ADC_Filter;

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
#define  IN_SYNC_BYTE_1	'A'
#define  IN_SYNC_BYTE_2 'R'

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;
ADC_HandleTypeDef hadc2;

TIM_HandleTypeDef htim2;
TIM_HandleTypeDef htim16;

UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */
uint8_t fw_rev_h = 0;
uint8_t fw_rev_l = 1;
uint8_t rx_hold_buffer[2];
uint8_t rx_buffer[32];
uint8_t tx_buffer[32];
uint8_t tx_len = 0x00;
uint8_t tx_len_counter = 0x00;
uint8_t rx_counter = 0x00;
uint8_t rx_len = 0x00;
uint8_t rx_len_counter = 0x00;
uint16_t rx_checksum = 0x0000;
uint16_t tx_checksum = 0x0000;
uint8_t rx_checksum_hold_1 = 0x00;
uint8_t rx_checksum_hold_2 = 0x00;
uint16_t rx_checksum_hold = 0x0000;
uint8_t power_state_value = 0x00;
uint8_t command = 0x00;
uint8_t adc_task_flag = 0x00;
float vdd_ref = 0;
uint32_t vdd_ref_uint = 0x00000000;
uint32_t v_target = 0x00000000;
uint8_t vset_task_flag = 0x00;
uint8_t serial_number_flag = 0x00;
uint8_t serial_number[19] = "ARRIVE-POWERSIM-001";
uint16_t pwm_value = 0x0000;
uint32_t pwm_value_store = 0x00000000;
uint32_t vout_adc_val = 0x0000000;
uint32_t filtered_adc = 0x0000000;
uint32_t pwm_max = 20000;
float vout = 0;
float vout_adj = 0;
uint32_t vout_adj_uint = 0x00000000;
uint8_t buffer_count = 0x00;
uint32_t v_scale = 0x00000000;
uint8_t solid_state_flag = 0x00;

/* Stored in RAM */
const uint16_t dataBuffer[25] =
{
  0x0000,
  0x000A,
  0x00B5,
  0x00C6,
  0x00D5,
  0x00E3,
  0x00F2,
  0x0100,
  0x010F,
  0x011E,
  0x012D,
  0x013D,
  0x014E,
  0x0163,
  0x017B,
  0x0195,
  0x01B2,
  0x01D0,
  0x01F6,
  0x021A,
  0x0244,
  0x0272,
  0x02A2,
  0x02D8,
  0x0311
};

ADC_Filter v_out_filter;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_ADC2_Init(void);
static void MX_TIM2_Init(void);
static void MX_ADC1_Init(void);
static void MX_TIM16_Init(void);
/* USER CODE BEGIN PFP */
void power_switch (uint8_t state);
void power_switch_solid_state (uint8_t state);
void adc_task(void);
float get_actual_vdda(ADC_HandleTypeDef *hadc);
void voltage_conversion_task(void);
void serial_number_task (void);
int32_t update_pwm(uint32_t measured_mv);
void ADC_Filter_Init(ADC_Filter *f);
uint32_t ADC_Filter_Update(ADC_Filter *f, uint32_t new_sample);

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_USART2_UART_Init();
  MX_ADC2_Init();
  MX_TIM2_Init();
  MX_ADC1_Init();
  MX_TIM16_Init();
  /* USER CODE BEGIN 2 */

  /*Configure GPIO pin output Level */
  HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);

  /* Run ADC calibration */
  HAL_ADCEx_Calibration_Start(&hadc1, ADC_SINGLE_ENDED);
  HAL_ADCEx_Calibration_Start(&hadc2, ADC_SINGLE_ENDED);

  /* Setup UART interrupts */
  /* Make sure UART Rx counters and flags are reset */
  rx_counter = 0x00;
  rx_len = 0x00;
  rx_len_counter = 0x00;
  adc_task_flag = 0x00;
  pwm_value = 0x0000;

  HAL_UART_Receive_IT(&huart2, rx_hold_buffer, 1);

  /* Get real VDDA value */
  vdd_ref = get_actual_vdda(&hadc1);

  /* Start output PWM at zero */
  __HAL_TIM_SET_COMPARE(&htim16, TIM_CHANNEL_1, 0);
  HAL_TIM_PWM_Start(&htim16, TIM_CHANNEL_1);

  ADC_Filter_Init(&v_out_filter);

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */

  while (1)
  {
	if (adc_task_flag == 0xff)
    {
      adc_task_flag = 0x00;

      tx_len = 0x04;

	  tx_buffer[0] = IN_SYNC_BYTE_1;
	  tx_buffer[1] = IN_SYNC_BYTE_2;
	  tx_buffer[2] = tx_len;
	  tx_buffer[3] = (uint8_t)((vout_adj_uint >> 24) & 0xFF);
	  tx_buffer[4] = (uint8_t)((vout_adj_uint >> 16) & 0xFF);
	  tx_buffer[5] = (uint8_t)((vout_adj_uint >> 8)  & 0xFF);
	  tx_buffer[6] = (uint8_t)(vout_adj_uint & 0xFF);

	  /* Need to apply checksum to all data bits */
	  for (tx_len_counter = 0x00; tx_len_counter < tx_len; tx_len_counter++)
	  {
	    tx_checksum += tx_buffer[tx_len_counter + 3];
	  }

	  tx_checksum = ~tx_checksum;

	  tx_buffer[7] = (uint8_t)((tx_checksum >> 8)  & 0xFF);
	  tx_buffer[8] = (uint8_t)(tx_checksum & 0xFF);

	  tx_len = 0x13;

	  HAL_UART_Transmit(&huart2, tx_buffer, tx_len, 100);
    }

	if (serial_number_flag == 0xff)
	{
	  serial_number_flag = 0x00;
	  serial_number_task ();
	}

	if (vset_task_flag == 0xff)
	{
	  adc_task();

	  filtered_adc = ADC_Filter_Update(&v_out_filter, vout_adc_val);

	  vout = ((float)filtered_adc / 4095.0f) * vdd_ref;

	  vout_adj = vout * 10.9f;

	  vout_adj_uint = (uint32_t)vout_adj;

	  pwm_value_store = update_pwm(vout_adj_uint);

	  pwm_value = (uint16_t)pwm_value_store;

	  __HAL_TIM_SET_COMPARE(&htim16, TIM_CHANNEL_1, pwm_value);
	}


	else
	{
	  if (solid_state_flag == 0x00)
	  {
		__HAL_TIM_SET_COMPARE(&htim16, TIM_CHANNEL_1, 0);
	  }
	}


    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }

  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = RCC_PLLM_DIV1;
  RCC_OscInitStruct.PLL.PLLN = 16;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2;
  RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief ADC1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_ADC1_Init(void)
{

  /* USER CODE BEGIN ADC1_Init 0 */

  /* USER CODE END ADC1_Init 0 */

  ADC_MultiModeTypeDef multimode = {0};
  ADC_ChannelConfTypeDef sConfig = {0};

  /* USER CODE BEGIN ADC1_Init 1 */

  /* USER CODE END ADC1_Init 1 */

  /** Common config
  */
  hadc1.Instance = ADC1;
  hadc1.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV32;
  hadc1.Init.Resolution = ADC_RESOLUTION_12B;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.GainCompensation = 0;
  hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
  hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  hadc1.Init.LowPowerAutoWait = DISABLE;
  hadc1.Init.ContinuousConvMode = DISABLE;
  hadc1.Init.NbrOfConversion = 1;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc1.Init.DMAContinuousRequests = DISABLE;
  hadc1.Init.Overrun = ADC_OVR_DATA_PRESERVED;
  hadc1.Init.OversamplingMode = DISABLE;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure the ADC multi-mode
  */
  multimode.Mode = ADC_MODE_INDEPENDENT;
  if (HAL_ADCEx_MultiModeConfigChannel(&hadc1, &multimode) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_VREFINT;
  sConfig.Rank = ADC_REGULAR_RANK_1;
  sConfig.SamplingTime = ADC_SAMPLETIME_640CYCLES_5;
  sConfig.SingleDiff = ADC_SINGLE_ENDED;
  sConfig.OffsetNumber = ADC_OFFSET_NONE;
  sConfig.Offset = 0;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN ADC1_Init 2 */

  /* USER CODE END ADC1_Init 2 */

}

/**
  * @brief ADC2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_ADC2_Init(void)
{

  /* USER CODE BEGIN ADC2_Init 0 */

  /* USER CODE END ADC2_Init 0 */

  ADC_ChannelConfTypeDef sConfig = {0};

  /* USER CODE BEGIN ADC2_Init 1 */

  /* USER CODE END ADC2_Init 1 */

  /** Common config
  */
  hadc2.Instance = ADC2;
  hadc2.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV32;
  hadc2.Init.Resolution = ADC_RESOLUTION_12B;
  hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc2.Init.GainCompensation = 0;
  hadc2.Init.ScanConvMode = ADC_SCAN_DISABLE;
  hadc2.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
  hadc2.Init.LowPowerAutoWait = DISABLE;
  hadc2.Init.ContinuousConvMode = DISABLE;
  hadc2.Init.NbrOfConversion = 1;
  hadc2.Init.DiscontinuousConvMode = DISABLE;
  hadc2.Init.ExternalTrigConv = ADC_SOFTWARE_START;
  hadc2.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
  hadc2.Init.DMAContinuousRequests = DISABLE;
  hadc2.Init.Overrun = ADC_OVR_DATA_PRESERVED;
  hadc2.Init.OversamplingMode = DISABLE;
  if (HAL_ADC_Init(&hadc2) != HAL_OK)
  {
    Error_Handler();
  }

  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_3;
  sConfig.Rank = ADC_REGULAR_RANK_1;
  sConfig.SamplingTime = ADC_SAMPLETIME_640CYCLES_5;
  sConfig.SingleDiff = ADC_SINGLE_ENDED;
  sConfig.OffsetNumber = ADC_OFFSET_NONE;
  sConfig.Offset = 0;
  if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN ADC2_Init 2 */

  /* USER CODE END ADC2_Init 2 */

}

/**
  * @brief TIM2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM2_Init(void)
{

  /* USER CODE BEGIN TIM2_Init 0 */

  /* USER CODE END TIM2_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM2_Init 1 */

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 12800-1;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 99;
  htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim2.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim2, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM2_Init 2 */

  /* USER CODE END TIM2_Init 2 */

}

/**
  * @brief TIM16 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM16_Init(void)
{

  /* USER CODE BEGIN TIM16_Init 0 */

  /* USER CODE END TIM16_Init 0 */

  TIM_OC_InitTypeDef sConfigOC = {0};
  TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig = {0};

  /* USER CODE BEGIN TIM16_Init 1 */

  /* USER CODE END TIM16_Init 1 */
  htim16.Instance = TIM16;
  htim16.Init.Prescaler = 1;
  htim16.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim16.Init.Period = 63999;
  htim16.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim16.Init.RepetitionCounter = 0;
  htim16.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim16) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_TIM_PWM_Init(&htim16) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = 0;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCNPolarity = TIM_OCNPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
  sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
  if (HAL_TIM_PWM_ConfigChannel(&htim16, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }
  sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_DISABLE;
  sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_DISABLE;
  sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_OFF;
  sBreakDeadTimeConfig.DeadTime = 0;
  sBreakDeadTimeConfig.BreakState = TIM_BREAK_DISABLE;
  sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_HIGH;
  sBreakDeadTimeConfig.BreakFilter = 0;
  sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
  if (HAL_TIMEx_ConfigBreakDeadTime(&htim16, &sBreakDeadTimeConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM16_Init 2 */

  /* USER CODE END TIM16_Init 2 */
  HAL_TIM_MspPostInit(&htim16);

}

/**
  * @brief USART2 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  huart2.Init.OneBitSampling = UART_ONE_BIT_SAMPLE_DISABLE;
  huart2.Init.ClockPrescaler = UART_PRESCALER_DIV1;
  huart2.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_UARTEx_SetTxFifoThreshold(&huart2, UART_TXFIFO_THRESHOLD_1_8) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_UARTEx_SetRxFifoThreshold(&huart2, UART_RXFIFO_THRESHOLD_1_8) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_UARTEx_DisableFifoMode(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
  /* USER CODE BEGIN MX_GPIO_Init_1 */

  /* USER CODE END MX_GPIO_Init_1 */

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : LD2_Pin */
  GPIO_InitStruct.Pin = LD2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct);

  /* USER CODE BEGIN MX_GPIO_Init_2 */

  /* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */
void ADC_Filter_Init(ADC_Filter *f)
{
  memset(f->buffer, 0, sizeof(f->buffer));
  f->sum = 0;
  f->index = 0;
}

uint32_t ADC_Filter_Update(ADC_Filter *f, uint32_t new_sample)
{
  /* Remove the oldest sample from the running sum */
  f->sum -= f->buffer[f->index];

  /* Store the new sample in the buffer */
  f->buffer[f->index] = new_sample;

  /* Add the new sample to the sum */
  f->sum += new_sample;

  /* Move index to next position, wrap around if at end */
  f->index++;

  if (f->index >= AVG_WINDOW)
  {
    f->index = 0;
  }

  /* Return the average */
  return f->sum / AVG_WINDOW;
}

int32_t update_pwm (uint32_t measured_mv)
{
  /* Calculate Error */
  int32_t new_pwm = 0;
  uint8_t direction_flag = 0x00;

  if (v_target >= measured_mv)
  {
    direction_flag = 0x00;
  }

  else
  {
    direction_flag = 0xFF;
  }

  if (direction_flag == 0xFF)
  {
	new_pwm = (uint32_t)pwm_value;
	new_pwm--;
  }

  else
  {
    new_pwm = (uint32_t)pwm_value;
	new_pwm++;
  }

  /* Output Saturation (Keep PWM within hardware limits) */
  if (new_pwm > pwm_max)
  {
	new_pwm = pwm_max;
  }

  if (new_pwm <= 1)
  {
    new_pwm = 1;
  }

  return new_pwm;
}

float get_actual_vdda(ADC_HandleTypeDef *hadc)
{
  uint32_t vrefint_raw = 0;

  /* Perform ADC reading of the VREFINT channel */
  HAL_ADC_Start(hadc);

  if (HAL_ADC_PollForConversion(hadc, 10) == HAL_OK)
  {
    vrefint_raw = HAL_ADC_GetValue(hadc);
  }

  HAL_ADC_Stop(hadc);

  if (vrefint_raw == 0)
  {
    return 0; /* Avoid division by zero */
  }

  /* Use the standard ST formula to calculate VDDA */
  /* VDDA = VREFINT_CAL_VREF * VREFINT_CAL / VREFINT_DATA */
  float vdda_mv = (VREFINT_CAL_VREF * (uint32_t)(*VREFINT_CAL_ADDR)) / (float)vrefint_raw;

  return vdda_mv;
}

void serial_number_task (void)
{
  tx_len = 0x13;

  tx_buffer[0] = IN_SYNC_BYTE_1;
  tx_buffer[1] = IN_SYNC_BYTE_2;

  for (tx_len_counter = 0x00; tx_len_counter < tx_len; tx_len_counter++)
  {
    tx_buffer[tx_len_counter + 3] = serial_number[tx_len_counter];
  }

  tx_buffer[tx_len + 3] = 0x3A;
  tx_buffer[tx_len + 4] = fw_rev_h + 0x30;
  tx_buffer[tx_len + 5] = fw_rev_l + 0x30;

  tx_len = 0x16;
  tx_buffer[2] = tx_len;

  tx_checksum = 0x00;

  /* Need to apply checksum to all data bits */
  for (tx_len_counter = 0x00; tx_len_counter < tx_len; tx_len_counter++)
  {
    tx_checksum += tx_buffer[tx_len_counter + 3];
  }

  tx_checksum = ~tx_checksum;

  tx_buffer[tx_len + 3] = (uint8_t)((tx_checksum >> 8)  & 0xFF);
  tx_buffer[tx_len + 4] = (uint8_t)(tx_checksum & 0xFF);

  tx_len = 0x1B;

  HAL_UART_Transmit(&huart2, tx_buffer, tx_len, 100);
}

/* ADC task */
void adc_task (void)
{
  HAL_ADC_Start(&hadc2);
  HAL_ADC_PollForConversion(&hadc2, 500);
  vout_adc_val = HAL_ADC_GetValue(&hadc2);
  HAL_ADC_Stop(&hadc2);
}

/* Power switch function */
void power_switch (uint8_t state)
{
  if (state == 1)
  {
	vset_task_flag = 0xFF;
	HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_SET);

	v_scale = v_target / 1000;

	buffer_count = (uint8_t)v_scale;

	pwm_value = dataBuffer[buffer_count];

	__HAL_TIM_SET_COMPARE(&htim16, TIM_CHANNEL_1, pwm_value);
  }

  else
  {
	vset_task_flag = 0x00;
	HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);
	__HAL_TIM_SET_COMPARE(&htim16, TIM_CHANNEL_1, 0);
  }
}

/* Power switch solid state function */
void power_switch_solid_state (uint8_t state)
{
  if (state == 1)
  {
	HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_SET);
	__HAL_TIM_SET_COMPARE(&htim16, TIM_CHANNEL_1, 63999);
  }

  else
  {
	HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);
	__HAL_TIM_SET_COMPARE(&htim16, TIM_CHANNEL_1, 0);
  }
}

/* UART Tx callback */
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
  /* Do nothing here for now */
}

/* UART Rx callback */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  /* If data received on UART */
  if(huart->Instance==USART2)
  {
	/* Act on received data */
	switch (rx_counter)
	{
	  case 0x00:
		/* Check to see if first sync byte has been received */
		if (rx_hold_buffer[0] == IN_SYNC_BYTE_1)
		{
		  /* Got it, so now wait for the second sync byte */
		  rx_counter++;
		}

	    break;

	  case 0x01:
		/* Check to see if second sync byte has been received */
		if (rx_hold_buffer[0] == IN_SYNC_BYTE_2)
		{
		  /* Got it, so now wait for the data byte */
		  rx_counter++;
		}

		else
		{
		  /* Not got the second sync byte */
		  /* If first sync byte found here, then still wait for second */
		  if (rx_hold_buffer[0] == IN_SYNC_BYTE_1)
		  {
		    /* Got it, so now wait for the second sync byte */
			rx_counter = 0x01;
		  }

		  /* Otherwise start again and wait for first sync byte */
		  else
		  {
		    rx_counter = 0x00;
		  }
		}

		break;

	  case 0x02:
		/* Get rx length and reset counter */
		rx_len = rx_hold_buffer[0];
		rx_len_counter = 0x00;
		rx_counter++;
	    break;

	  case 0x03:
		/* Store entire length of Data bytes */
		/* Increase count */
		rx_len_counter++;

		/* Store data */
		rx_buffer[rx_len_counter - 1] = rx_hold_buffer[0];

		/* Check to see if we have all the expected data bytes */
		/* If so, then move on the CRC */
		if (rx_len_counter == rx_len)
		{
		  rx_counter++;
		  rx_len_counter = 0x00;
		}

		break;

	  case 0x04:
		/* Store Rx checksum byte #1 */
		rx_checksum_hold_1 = rx_hold_buffer[0];
		rx_counter++;
		break;

	  case 0x05:
	    /* Store Rx checksum byte #2, reset and calculate checksum */
		rx_checksum_hold_2 = rx_hold_buffer[0];

		rx_checksum_hold = (rx_checksum_hold_1 << 8) | rx_checksum_hold_2;

		rx_checksum = 0;

		/* Need to apply to all data bits */
		for (rx_len_counter = 0x00; rx_len_counter < rx_len; rx_len_counter++)
		{
			rx_checksum += rx_buffer[rx_len_counter];
		}

		rx_len = 0x00;
		rx_len_counter = 0x00;

		rx_checksum = ~rx_checksum;

		/* If checksum calculated equals the received checksum of packet then we got a good packet */
		if (rx_checksum == rx_checksum_hold)
		{
		  /* Rx is finished, so reset count to wait for another first sync byte (also act on command/data)*/
		  rx_counter = 0x00;

		  command = rx_buffer[0];

		  switch (command)
		  {
		    /* 'S' - Set power output state */
		    case 0x53:
		      solid_state_flag = 0x00;
			  power_state_value = rx_buffer[1];
			  v_target = ((uint32_t)rx_buffer[2] << 24) | ((uint32_t)rx_buffer[3] << 16) | ((uint32_t)rx_buffer[4] << 8)  | ((uint32_t)rx_buffer[5]);
			  power_switch(power_state_value);
			  break;

			/* 's' - Set power output solid state */
			case 0x73:
			  solid_state_flag = 0xff;
			  power_state_value = rx_buffer[1];
			  power_switch_solid_state(power_state_value);
			  break;

			/* 'V' - Get voltages (both input and output) */
		    case 0x56:
		      adc_task_flag = 0xff;
		      break;

		    /* 'I' - Get serial number information */
		    case 0x49:
		      serial_number_flag = 0xff;
		      break;

		    default:
		      break;
		  }
		}

		/* Bad packet received */
		else
		{
		  /* Rx is finished, so reset count to wait for another first sync byte (bad packet so no flag)*/
		  rx_counter = 0x00;
		}

		break;

	  /* Default case - NOT USED!*/
	  default:
	    break;
	}

	/* Reset interrupts */
	HAL_UART_Receive_IT(&huart2, rx_hold_buffer, 1);
  }
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
