
/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
 * All rights reserved.</center></h2>
 *
 * This software component is licensed by ST under BSD 3-Clause license,
 * the "License"; You may not use this file except in compliance with the
 * License. You may obtain a copy of the License at:
 *                        opensource.org/licenses/BSD-3-Clause
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "libSerial/serial.h"
#include "libPLX/plx.h"
#include "misc.h"

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
#define ADC_CHANNELS 7

#define ADC_MAP_CHAN 2

#define ADC_PRESSURE_CHAN 3

#define ADC_REF_CHAN 5

#define ADC_TEMP_CHAN 6

// with a dwell angle of 45 degrees , 4 cylinders and a maximum RPM of 5000
// freq = 5000/60 * 2 = 166Hz.
// the TIM2 counter counts in 10uS increments,
// TODO this is wrong algo. Accept FIRST pulse, skip shorter pulses
// Accept the first pulse with over 2.5mS (1/400 sec)  duration as the closure
#define BREAKER_MIN (RPM_COUNT_RATE/400)

#define RPM_AVERAGE 4

// wait for about 1 second to decide whether or not starter is on

#define STARTER_LIMIT 10


/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc1;
DMA_HandleTypeDef hdma_adc1;

CAN_HandleTypeDef hcan;

SPI_HandleTypeDef hspi1;

TIM_HandleTypeDef htim2;
TIM_HandleTypeDef htim3;
TIM_HandleTypeDef htim4;

UART_HandleTypeDef huart1;

/* USER CODE BEGIN PV */


volatile char TimerFlag = 0;

volatile char NoSerialInCTR = 0; // Missing characters coming in on USART1
volatile char NoSerialIn = 0;

// scale for filtered samples
#define Scale 1024.0

// storage for ADC
uint16_t ADC_Samples[ADC_CHANNELS] = { [0 ... ADC_CHANNELS-1] = 0 };

uint32_t FILT_Samples[ADC_CHANNELS] = { [0 ... ADC_CHANNELS-1] = 0 }; // filtered ADC samples * Scale


#define NOM_VREF 3.3
// initial ADC vref
float  adc_vref   = NOM_VREF;

// internal bandgap voltage reference
const float STM32REF = 1.2;           // 1.2V typical

// scale factor initially assuming
float ADC_Scale = 1/(Scale * 4096) * NOM_VREF ;

// Rev counter processing from original RevCounter Project
uint16_t RPM_Diff = 0;
uint16_t RPM_Count_Latch = 0;
// accumulators
uint16_t RPM_Pulsecount = 0;
unsigned int RPM_FilteredWidth = 0;

// last time we detected end of dwell i.e. ignition pulse
uint16_t last_dwell_end = 0;
uint16_t RPM_Period[RPM_AVERAGE];
unsigned int RPM_Period_Ptr = 0;

unsigned int Coded_RPM = 0;
unsigned int Coded_CHT = 0;

uint32_t PowerTempTimer;

uint16_t Starter_Debounce = 0;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_ADC1_Init(void);
static void MX_CAN_Init(void);
static void MX_SPI1_Init(void);
static void MX_TIM2_Init(void);
static void MX_TIM3_Init(void);
static void MX_TIM4_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

void
plx_sendword (int x)
{
  PutCharSerial (&uc1, ((x) >> 6) & 0x3F);
  PutCharSerial (&uc1, (x) & 0x3F);
}

void
filter_ADC_samples ()
{
  int i;
  for (i = 0; i < ADC_CHANNELS; i++)
    {
      FILT_Samples[i] += (ADC_Samples[i] * Scale - FILT_Samples[i]) / 2;
    }
}


/****!
 * @brief this reads the reference voltage within the STM32L151
 * Powers up reference voltage and temperature sensor, waits 3mS  and takes reading
 * Requires that the ADC be powered up
 */


void
CalibrateADC (void)
{
  float adc_val = FILT_Samples[ADC_REF_CHAN]  ;       // as set up in device config

  float adc_vref = STM32REF * ( 4096.0 * Scale)/  adc_val; // the estimate for checking

  ADC_Scale = 1/(Scale * 4096) * adc_vref ;


}



void
ProcessRPM (int instance)
{
// compute the timer values
// snapshot timers
   unsigned short RPM_Pulsewidth;
  // current RPM pulse next slot index
  unsigned short RPM_Count_Val;
  __disable_irq (); // copy the counter value
  RPM_Count_Val = RPM_Count;
  __enable_irq ();
// do calculations
// if there is only one entry, cannot get difference
  if (RPM_Count_Latch != RPM_Count_Val)
    {
      while (1)
	{
	  unsigned int base_time;
	  unsigned int new_time;
	  // if we are at N-1, stop.
	  unsigned int next_count = (RPM_Count_Latch + 1) % RPM_SAMPLES;
	  if (next_count == RPM_Count_Val)
	    {
	      break; // completed loop
	    }
	  char pulse_level = RPM_Level[RPM_Count_Latch];
	  base_time = RPM_Time[RPM_Count_Latch];
	  new_time = RPM_Time[next_count];
	  RPM_Count_Latch = next_count;

	  RPM_Pulsewidth = new_time - base_time; // not wrapped

	  // if the pulse was low,
	  if (pulse_level == 0 && RPM_Pulsewidth > BREAKER_MIN)
	    {

	      RPM_Diff = new_time - last_dwell_end;

	      RPM_Period[RPM_Period_Ptr] = RPM_Diff;
	      RPM_Period_Ptr = (RPM_Period_Ptr + 1) % RPM_AVERAGE;
	      if (RPM_Pulsecount < RPM_AVERAGE)
		RPM_Pulsecount++; // count one pulse
	      last_dwell_end = new_time;

	    }
	}

    }

  if (RPM_Pulsecount == RPM_AVERAGE)
    {
      // now have time for N pulses in clocks
      // need to scale by 19.55: one unit is 19.55 RPM
      // 1Hz is 30 RPM
      int i;
      RPM_FilteredWidth = 0;
      for (i = 0; i < RPM_AVERAGE; i++)
	RPM_FilteredWidth += RPM_Period[i];

      Coded_RPM = (Scale * 30.0 * RPM_AVERAGE * RPM_COUNT_RATE)
	  / (19.55 * RPM_FilteredWidth);

#if !defined MY_DEBUG
      // reset here unless we want to debug
      RPM_Pulsecount = 0;
      RPM_FilteredWidth = 0;
#endif
    }

// send the current RPM *calculation
  plx_sendword (PLX_RPM);
  PutCharSerial (&uc1, instance);
  plx_sendword (Coded_RPM / Scale);
}

// this uses a MAX6675 which is a simple 16 bit read
// SPI is configured for 8 bits so I can use an OLED display if I need it
// must wait > 0.22 seconds between conversion attempts as this is the measurement time
//

FunctionalState CHT_Enable = ENABLE;

#define CORR 3

uint16_t Temp_Observations[NUM_SPI_TEMP_SENS] = { [0 ... NUM_SPI_TEMP_SENS-1] = 0 };


/// \param item The array index to send
/// \param instance The instance to send over the bus
/// \param type the code to use for this observation
void
ProcessTemp (char item, int instance, enum PLX_Observations type)
{
  if (item > NUM_SPI_TEMP_SENS)
    return;
  plx_sendword (type);
  PutCharSerial (&uc1, instance);
  plx_sendword (Temp_Observations[item]);

}


/// \brief Reset the temperature chip select system
void resetTempCS(void)
{
     HAL_GPIO_WritePin (SPI_CS_D_GPIO_Port, SPI_CS_D_Pin, GPIO_PIN_SET);
     HAL_GPIO_WritePin (SPI_CS_Clk_GPIO_Port, SPI_CS_Clk_Pin,
			 GPIO_PIN_SET);

     for (int i = 0 ; i < 4; i++)
       {
	     HAL_GPIO_WritePin (SPI_CS_Clk_GPIO_Port, SPI_CS_Clk_Pin,
				 GPIO_PIN_RESET);
	     HAL_GPIO_WritePin (SPI_CS_Clk_GPIO_Port, SPI_CS_Clk_Pin,
				 GPIO_PIN_SET);
       }

     // prepare for selecting next pin
     HAL_GPIO_WritePin (SPI_CS_D_GPIO_Port, SPI_CS_D_Pin, GPIO_PIN_RESET);

}

void nextTempCS(void)
{
  HAL_GPIO_WritePin (SPI_CS_Clk_GPIO_Port, SPI_CS_Clk_Pin,
			 GPIO_PIN_RESET);
  HAL_GPIO_WritePin (SPI_CS_Clk_GPIO_Port, SPI_CS_Clk_Pin,
			 GPIO_PIN_SET);
  HAL_GPIO_WritePin (SPI_CS_D_GPIO_Port, SPI_CS_D_Pin, GPIO_PIN_SET);
}

void
EnableTempSensors (FunctionalState state)

{
  GPIO_InitTypeDef GPIO_InitStruct;

  CHT_Enable = state;

  /* enable SPI in live mode : assume it and its GPIOs are already initialised in SPI mode */
  if (state == ENABLE)
    {
      HAL_GPIO_WritePin (ENA_AUX_5V_GPIO_Port, ENA_AUX_5V_Pin, GPIO_PIN_SET);

      resetTempCS();

      /* put the SPI pins back into SPI AF mode */
      GPIO_InitStruct.Pin = SPI1_MOSI_Pin | SPI1_MISO_Pin | SPI1_SCK_Pin;
      GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
      GPIO_InitStruct.Pull = GPIO_NOPULL;
      GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
      HAL_GPIO_Init (SPI1_SCK_GPIO_Port, &GPIO_InitStruct);

    }
  else
    {
      /*  Power down the SPI interface taking signals all low */
      HAL_GPIO_WritePin (ENA_AUX_5V_GPIO_Port, ENA_AUX_5V_Pin, GPIO_PIN_RESET);

      HAL_GPIO_WritePin (SPI1_SCK_GPIO_Port,
			 SPI1_MOSI_Pin | SPI1_MISO_Pin | SPI1_SCK_Pin,
			 GPIO_PIN_RESET);

      /* put the SPI pins back into GPIO mode */
      GPIO_InitStruct.Pin = SPI1_MOSI_Pin | SPI1_MISO_Pin | SPI1_SCK_Pin;
      GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
      GPIO_InitStruct.Pull = GPIO_NOPULL;
      GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
      HAL_GPIO_Init (SPI1_SCK_GPIO_Port, &GPIO_InitStruct);

    }

}

// 1023 is 20.00 volts.
void
ProcessBatteryVoltage (int instance)
{
  float reading = FILT_Samples[instance] * ADC_Scale;
  reading = reading * 7.8125; // real voltage
  reading = reading * 51.15; // PLC scaling =  1023/20

  plx_sendword (PLX_Volts);
  PutCharSerial (&uc1, instance);
  plx_sendword ((uint16_t) reading);

}


void
ProcessCPUTemperature (int instance)
{
   // this is defined in the STM32F103 reference manual . #
  // V25 = 1.43 volts
  // Avg_slope = 4.3mV /degree C
  // temperature = {(V25 - VSENSE) / Avg_Slope} + 25

  /* get the ADC reading corresponding to ADC channel 16 after turning on the ADC */

  float temp_val = FILT_Samples[ADC_TEMP_CHAN] * ADC_Scale;
  /* renormalise temperature value to account for different ADC Vref  : normalise to that which we would get for a 3000mV reference */
  temp_val = (1.43- temp_val) / 4.3e-3 + 25;

  int32_t result = temp_val  ;

//  int32_t result = 800 * ((int32_t) temp_val - TS_CAL30);
//  result = result / (TS_CAL110 - TS_CAL30) + 300;


  plx_sendword (PLX_FluidTemp);
  PutCharSerial (&uc1, instance);
  plx_sendword (result);

}

// the MAP sensor is giving us a reading of
// 4.6 volts for 1019mB or 2.27 volts at the ADC input (resistive divider by 2.016)
// I believe the sensor reads  4.5V at 1000kPa and 0.5V at  0kPa
// Calibration is a bit off
// Real   Displayed
// 989    968
// 994.1    986
// 992.3  984

void
ProcessMAP (int instance)
{
// Using ADC_Samples[3] as the MAP input
  float reading = FILT_Samples[ADC_MAP_CHAN] * ADC_Scale;
  reading = reading * 2.016;      // real voltage
  // values computed from slope / intercept of map.ods
  //reading = (reading) * 56.23 + 743.2; // do not assume 0.5 volt offset : reading from 0 to 4.5 instead of 0.5 to 4.5
  // using a pressure gauge.
  reading = (reading) * 150 + 326;

  plx_sendword (PLX_MAP);
  PutCharSerial (&uc1, instance);
  plx_sendword ((uint16_t) reading);

}

// the Oil pressi sensor is giving us a reading of
// 4.5 volts for 100 PSI or  2.25 volts at the ADC input (resistive divider by 2.016)
// I believe the sensor reads  4.5V at 100PSI and 0.5V at  0PSI
// an observation of 1024 is 200PSI, so observation of 512 is 100 PSI.

void
ProcessOilPress (int instance)
{
// Using ADC_Samples[2] as the MAP input
  float reading = FILT_Samples[ADC_PRESSURE_CHAN] * ADC_Scale;
  reading = reading * 2.00; // real voltage
  reading = (reading - 0.5) * 512 / 4;  // this is 1023 * 100/200

  plx_sendword (PLX_FluidPressure);
  PutCharSerial (&uc1, instance);
  plx_sendword ((uint16_t) reading);

}

void
ProcessTiming (int instance)
{
  plx_sendword (PLX_Timing);
  PutCharSerial (&uc1, instance);
  plx_sendword (64 - 15); // make it negative
}

/* 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_DMA_Init();
  MX_ADC1_Init();
  MX_CAN_Init();
  MX_SPI1_Init();
  MX_TIM2_Init();
  MX_TIM3_Init();
  MX_TIM4_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
  HAL_MspInit ();

  // Not using HAL USART code
  __HAL_RCC_USART1_CLK_ENABLE()
  ; // PLX comms port
  /* setup the USART control blocks */
  init_usart_ctl (&uc1, huart1.Instance);

  EnableSerialRxInterrupt (&uc1);

  HAL_SPI_MspInit (&hspi1);

  HAL_ADC_MspInit (&hadc1);

  HAL_ADC_Start_DMA (&hadc1, (uint32_t *)ADC_Samples, ADC_CHANNELS);

  HAL_ADC_Start_IT (&hadc1);

  HAL_TIM_Base_MspInit (&htim4);
  HAL_TIM_Base_Start_IT (&htim4);

  // initialise all the STMCubeMX stuff
  HAL_TIM_Base_MspInit (&htim2);
  // Start the counter
  HAL_TIM_Base_Start (&htim2);
  // Start the input capture and the rising edge interrupt
  HAL_TIM_IC_Start_IT (&htim2, TIM_CHANNEL_1);
  // Start the input capture and the falling edge interrupt
  HAL_TIM_IC_Start_IT (&htim2, TIM_CHANNEL_2);

  HAL_TIM_Base_MspInit (&htim3);
  __HAL_TIM_ENABLE_IT(&htim3, TIM_IT_UPDATE);
  uint32_t Ticks = HAL_GetTick () + 100;
  int CalCounter = 0;

  PowerTempTimer = HAL_GetTick () + 1000; /* wait 10 seconds before powering up the CHT sensor */

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
    {
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */

      if (HAL_GetTick () > Ticks)
	{
	  Ticks += 100;
	  filter_ADC_samples ();
	  // delay to calibrate ADC
	  if (CalCounter < 1000)
	    {
	      CalCounter += 100;
	    }

	  if (CalCounter == 900)
	    {
	      CalibrateADC ();
	    }
	}
      /* when the starter motor is on then power down the CHT sensors as they seem to fail */

      if (HAL_GPIO_ReadPin (STARTER_ON_GPIO_Port, STARTER_ON_Pin)
	  == GPIO_PIN_RESET)
	{
	  if (Starter_Debounce < STARTER_LIMIT)
	    {
	      Starter_Debounce++;
	    }
	}
      else
	{
	  if (Starter_Debounce > 0)
	    {
	      Starter_Debounce--;
	    }
	}

      if (Starter_Debounce == STARTER_LIMIT)
	{
	  EnableTempSensors (DISABLE);
	  PowerTempTimer = HAL_GetTick () + 1000;
	}
      else
      /* if the PowerTempTimer is set then wait for it to timeout, then power up CHT */
	{
	  if ((PowerTempTimer > 0) && (HAL_GetTick () > PowerTempTimer))
	    {
	      EnableTempSensors (ENABLE);
	      PowerTempTimer = 0;
	    }
	}

      // check to see if we have any incoming data, copy and append if so, if no data then create our own frames.
      int c;
      char send = 0;

      // poll the  input for a stop bit or timeout
      if (PollSerial (&uc1))
	{
	  resetSerialTimeout ();
	  c = GetCharSerial (&uc1);
	  if (c != PLX_Stop)
	    {
	      PutCharSerial (&uc1, c); // echo all but the stop bit
	    }
	  else
	    { // must be a stop character
	      send = 1; // start our sending process.
	    }
	}

      // sort out auto-sending
      if (TimerFlag)
	{
	  TimerFlag = 0;
	  if (NoSerialIn)
	    {
	      PutCharSerial (&uc1, PLX_Start);
	      send = 1;
	    }
	}
      if (send)
	{
	  send = 0;

	  // send the observations
	  ProcessRPM (0);
	  ProcessTemp (0,0,PLX_X_CHT);
	  ProcessTemp (1,1,PLX_X_CHT);
	  ProcessTemp (2,0,PLX_AIT);
	  ProcessTemp (3,1,PLX_AIT);
	  ProcessBatteryVoltage (0); // Batt 1
	  ProcessBatteryVoltage (1); // Batt 2
	  ProcessCPUTemperature (0); //  built in temperature sensor

	  ProcessMAP (0);
	  ProcessOilPress (0);

	  PutCharSerial (&uc1, PLX_Stop);
	}
    }


  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  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_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
  PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV6;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != 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_ChannelConfTypeDef sConfig = {0};

  /* USER CODE BEGIN ADC1_Init 1 */

  /* USER CODE END ADC1_Init 1 */
  /** Common config
  */
  hadc1.Instance = ADC1;
  hadc1.Init.ScanConvMode = ADC_SCAN_ENABLE;
  hadc1.Init.ContinuousConvMode = DISABLE;
  hadc1.Init.DiscontinuousConvMode = DISABLE;
  hadc1.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T3_TRGO;
  hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc1.Init.NbrOfConversion = 7;
  if (HAL_ADC_Init(&hadc1) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_0;
  sConfig.Rank = ADC_REGULAR_RANK_1;
  sConfig.SamplingTime = ADC_SAMPLETIME_71CYCLES_5;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_1;
  sConfig.Rank = ADC_REGULAR_RANK_2;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_2;
  sConfig.Rank = ADC_REGULAR_RANK_3;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_3;
  sConfig.Rank = ADC_REGULAR_RANK_4;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_4;
  sConfig.Rank = ADC_REGULAR_RANK_5;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_VREFINT;
  sConfig.Rank = ADC_REGULAR_RANK_6;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure Regular Channel
  */
  sConfig.Channel = ADC_CHANNEL_TEMPSENSOR;
  sConfig.Rank = ADC_REGULAR_RANK_7;
  if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN ADC1_Init 2 */

  /* USER CODE END ADC1_Init 2 */

}

/**
  * @brief CAN Initialization Function
  * @param None
  * @retval None
  */
static void MX_CAN_Init(void)
{

  /* USER CODE BEGIN CAN_Init 0 */

  /* USER CODE END CAN_Init 0 */

  /* USER CODE BEGIN CAN_Init 1 */

  /* USER CODE END CAN_Init 1 */
  hcan.Instance = CAN1;
  hcan.Init.Prescaler = 16;
  hcan.Init.Mode = CAN_MODE_NORMAL;
  hcan.Init.SyncJumpWidth = CAN_SJW_1TQ;
  hcan.Init.TimeSeg1 = CAN_BS1_1TQ;
  hcan.Init.TimeSeg2 = CAN_BS2_1TQ;
  hcan.Init.TimeTriggeredMode = DISABLE;
  hcan.Init.AutoBusOff = DISABLE;
  hcan.Init.AutoWakeUp = DISABLE;
  hcan.Init.AutoRetransmission = DISABLE;
  hcan.Init.ReceiveFifoLocked = DISABLE;
  hcan.Init.TransmitFifoPriority = DISABLE;
  if (HAL_CAN_Init(&hcan) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN CAN_Init 2 */

  /* USER CODE END CAN_Init 2 */

}

/**
  * @brief SPI1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_SPI1_Init(void)
{

  /* USER CODE BEGIN SPI1_Init 0 */

  /* USER CODE END SPI1_Init 0 */

  /* USER CODE BEGIN SPI1_Init 1 */

  /* USER CODE END SPI1_Init 1 */
  /* SPI1 parameter configuration*/
  hspi1.Instance = SPI1;
  hspi1.Init.Mode = SPI_MODE_MASTER;
  hspi1.Init.Direction = SPI_DIRECTION_2LINES;
  hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
  hspi1.Init.NSS = SPI_NSS_SOFT;
  hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
  hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  hspi1.Init.CRCPolynomial = 10;
  if (HAL_SPI_Init(&hspi1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN SPI1_Init 2 */

  /* USER CODE END SPI1_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};
  TIM_IC_InitTypeDef sConfigIC = {0};

  /* USER CODE BEGIN TIM2_Init 1 */

  /* USER CODE END TIM2_Init 1 */
  htim2.Instance = TIM2;
  htim2.Init.Prescaler = 719;
  htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim2.Init.Period = 65535;
  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();
  }
  if (HAL_TIM_IC_Init(&htim2) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_RISING;
  sConfigIC.ICSelection = TIM_ICSELECTION_DIRECTTI;
  sConfigIC.ICPrescaler = TIM_ICPSC_DIV1;
  sConfigIC.ICFilter = 15;
  if (HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigIC.ICPolarity = TIM_INPUTCHANNELPOLARITY_FALLING;
  sConfigIC.ICSelection = TIM_ICSELECTION_INDIRECTTI;
  sConfigIC.ICFilter = 0;
  if (HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL_2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM2_Init 2 */

  /* USER CODE END TIM2_Init 2 */

}

/**
  * @brief TIM3 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM3_Init(void)
{

  /* USER CODE BEGIN TIM3_Init 0 */

  /* USER CODE END TIM3_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};
  TIM_OC_InitTypeDef sConfigOC = {0};

  /* USER CODE BEGIN TIM3_Init 1 */

  /* USER CODE END TIM3_Init 1 */
  htim3.Instance = TIM3;
  htim3.Init.Prescaler = 719;
  htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim3.Init.Period = 199;
  htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim3.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_TIM_OC_Init(&htim3) != HAL_OK)
  {
    Error_Handler();
  }
  if (HAL_TIM_OnePulse_Init(&htim3, TIM_OPMODE_SINGLE) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_OC1;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sConfigOC.OCMode = TIM_OCMODE_TIMING;
  sConfigOC.Pulse = 198;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  if (HAL_TIM_OC_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM3_Init 2 */

  /* USER CODE END TIM3_Init 2 */

}

/**
  * @brief TIM4 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM4_Init(void)
{

  /* USER CODE BEGIN TIM4_Init 0 */

  /* USER CODE END TIM4_Init 0 */

  TIM_ClockConfigTypeDef sClockSourceConfig = {0};
  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM4_Init 1 */

  /* USER CODE END TIM4_Init 1 */
  htim4.Instance = TIM4;
  htim4.Init.Prescaler = 719;
  htim4.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim4.Init.Period = 9999;
  htim4.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  htim4.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim4) != HAL_OK)
  {
    Error_Handler();
  }
  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim4, &sClockSourceConfig) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim4, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM4_Init 2 */

  /* USER CODE END TIM4_Init 2 */

}

/**
  * @brief USART1 Initialization Function
  * @param None
  * @retval None
  */
static void MX_USART1_UART_Init(void)
{

  /* USER CODE BEGIN USART1_Init 0 */

  /* USER CODE END USART1_Init 0 */

  /* USER CODE BEGIN USART1_Init 1 */

  /* USER CODE END USART1_Init 1 */
  huart1.Instance = USART1;
  huart1.Init.BaudRate = 19200;
  huart1.Init.WordLength = UART_WORDLENGTH_8B;
  huart1.Init.StopBits = UART_STOPBITS_1;
  huart1.Init.Parity = UART_PARITY_NONE;
  huart1.Init.Mode = UART_MODE_TX_RX;
  huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart1.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart1) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART1_Init 2 */

  /* USER CODE END USART1_Init 2 */

}

/**
  * Enable DMA controller clock
  */
static void MX_DMA_Init(void)
{

  /* DMA controller clock enable */
  __HAL_RCC_DMA1_CLK_ENABLE();

  /* DMA interrupt init */
  /* DMA1_Channel1_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);

}

/**
  * @brief GPIO Initialization Function
  * @param None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOD_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LED_Blink_GPIO_Port, LED_Blink_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, SPI_CS_D_Pin|SPI_CS_Clk_Pin|ENA_AUX_5V_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin : LED_Blink_Pin */
  GPIO_InitStruct.Pin = LED_Blink_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LED_Blink_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pins : SPI_CS_D_Pin SPI_CS_Clk_Pin ENA_AUX_5V_Pin */
  GPIO_InitStruct.Pin = SPI_CS_D_Pin|SPI_CS_Clk_Pin|ENA_AUX_5V_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

  /*Configure GPIO pin : STARTER_ON_Pin */
  GPIO_InitStruct.Pin = STARTER_ON_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(STARTER_ON_GPIO_Port, &GPIO_InitStruct);

}

/* USER CODE BEGIN 4 */

/* 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 */

  /* 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,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/