
/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * <h2><center>&copy; Copyright (c) 2020 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 */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc;
DMA_HandleTypeDef hdma_adc;

SPI_HandleTypeDef hspi1;

TIM_HandleTypeDef htim2;
TIM_HandleTypeDef htim3;
TIM_HandleTypeDef htim6;

UART_HandleTypeDef huart1;
UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/

// with a dwell angle of 45 degrees , 4 cylinders and a maximum RPM of 5000
// freq = 5000/60 * 2 = 166Hz. Because the breaker might bounce , we accept the first pulse longer than 1/300 of a second as being a proper closure .
// the TIM2 counter counts in 10uS increments,
// TODO this is wrong algo. Accept FIRST pulse, skip shorter pulses
#define BREAKER_MIN (RPM_COUNT_RATE/300)

#define RPM_AVERAGE 4

// wait for about 1 second to decide whether or not starter is on

#define STARTER_LIMIT 10

volatile char TimerFlag = 0;

volatile char NoSerialInCTR = 0; // Missing characters coming in on USART1
volatile char NoSerialIn = 0;

// storage for ADC
uint16_t ADC_Samples[6];

#define Scale 1024.0
const float ADC_Scale = 3.3 / (Scale * 4096.0); // convert to a voltage

uint32_t FILT_Samples[6]; // filtered ADC samples * 1024
// 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 Power_CHT_Timer;

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_ADC_Init(void);
static void MX_SPI1_Init(void);
static void MX_TIM2_Init(void);
static void MX_TIM6_Init(void);
static void MX_USART1_UART_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_TIM3_Init(void);
/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/

/* 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
init_ADC_filter ()
{
  int i;
  for (i = 0; i < 6; i++)
    {
      FILT_Samples[i] = 0;
    }
}

void
filter_ADC_samples ()
{
  int i;
  for (i = 0; i < 6; i++)
    {
      FILT_Samples[i] += (ADC_Samples[i] * Scale - FILT_Samples[i]) / 2;
    }
}

void
ProcessRPM (int instance)
{
// compute the timer values
// snapshot timers
  unsigned long RPM_Pulsewidth;
  // current RPM pulse next slot index
  unsigned long 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 CHT_Observations[2] =
  { 0, 0 };

// look for the trigger pin being high then low - the points
// are opening, and skip the reading

void
ProcessCHT (int instance)
{
  plx_sendword (PLX_X_CHT);
  PutCharSerial (&uc1, instance);
  plx_sendword (CHT_Observations[instance]);

}

void
EnableCHT (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);
      HAL_GPIO_WritePin (SPI_NS_Temp_GPIO_Port, SPI_NS_Temp_Pin, GPIO_PIN_SET);
      HAL_GPIO_WritePin (SPI_NS_Temp2_GPIO_Port, SPI_NS_Temp2_Pin,
			 GPIO_PIN_SET);

      /* 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_VERY_HIGH;
      GPIO_InitStruct.Alternate = GPIO_AF5_SPI1;
      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 (SPI_NS_Temp_GPIO_Port, SPI_NS_Temp_Pin,
			 GPIO_PIN_RESET);
      HAL_GPIO_WritePin (SPI_NS_Temp2_GPIO_Port, SPI_NS_Temp2_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_VERY_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; // 1023/20

  plx_sendword (PLX_Volts);
  PutCharSerial (&uc1, instance);
  plx_sendword ((uint16_t) reading);

}

/****!
 * @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
 */

uint32_t ADC_VREF_MV = 3300;           // 3.300V typical
const uint16_t STM32REF_MV = 1224;           // 1.224V typical

void
CalibrateADC (void)
{
  uint32_t adc_val = FILT_Samples[5];       // as set up in device config
  ADC_VREF_MV = (STM32REF_MV * 4096) / adc_val;
}

void
ProcessCPUTemperature (int instance)
{
  int32_t temp_val;

  uint16_t TS_CAL30 = *(uint16_t*) (0x1FF8007AUL); /* ADC reading for temperature sensor at 30 degrees C with Vref = 3000mV */
  uint16_t TS_CAL110 = *(uint16_t*) (0x1FF8007EUL); /* ADC reading for temperature sensor at 110 degrees C with Vref = 3000mV */
  /* get the ADC reading corresponding to ADC channel 16 after turning on the ADC */

  temp_val = FILT_Samples[5];

  /* renormalise temperature value to account for different ADC Vref  : normalise to that which we would get for a 3000mV reference */
  temp_val = temp_val * ADC_VREF_MV / (Scale * 3000UL);

  int32_t result = 800 * ((int32_t) temp_val - TS_CAL30);
  result = result / (TS_CAL110 - TS_CAL30) + 300;

  if (result < 0)
    {
      result = 0;
    }
  plx_sendword (PLX_FluidTemp);
  PutCharSerial (&uc1, instance);
  plx_sendword (result / 10);

}

// 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[3] * 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[2] * 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_ADC_Init();
  MX_SPI1_Init();
  MX_TIM2_Init();
  MX_TIM6_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  MX_TIM3_Init();
  /* USER CODE BEGIN 2 */
  HAL_MspInit ();

// Not using HAL USART code
  __HAL_RCC_USART1_CLK_ENABLE()
  ; // PLX comms port
  __HAL_RCC_USART2_CLK_ENABLE()
  ;  // Debug comms port
  /* setup the USART control blocks */
  init_usart_ctl (&uc1, huart1.Instance);
  init_usart_ctl (&uc2, huart2.Instance);

  EnableSerialRxInterrupt (&uc1);
  EnableSerialRxInterrupt (&uc2);

  HAL_SPI_MspInit (&hspi1);

  HAL_ADC_MspInit (&hadc);

  HAL_ADC_Start_DMA (&hadc, ADC_Samples, 6);

  HAL_ADC_Start_IT (&hadc);

  HAL_TIM_Base_MspInit (&htim6);
  HAL_TIM_Base_Start_IT (&htim6);

// initialise all the STMCubeMX stuff
  HAL_TIM_Base_MspInit (&htim2);
// Start the counter
  HAL_TIM_Base_Start (&htim2);
// Start the input capture and the interrupt
  HAL_TIM_IC_Start_IT (&htim2, TIM_CHANNEL_1);

  HAL_TIM_Base_MspInit (&htim3);
  __HAL_TIM_ENABLE_IT(&htim3, TIM_IT_UPDATE);
  uint32_t Ticks = HAL_GetTick () + 100;
  int CalCounter = 0;

  Power_CHT_Timer = 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)
	{
	  EnableCHT (DISABLE);
	  Power_CHT_Timer = HAL_GetTick () + 1000;
	}
      else
      /* if the Power_CHT_Timer is set then wait for it to timeout, then power up CHT */
	{
	  if ((Power_CHT_Timer > 0) && (HAL_GetTick () > Power_CHT_Timer))
	    {
	      EnableCHT (ENABLE);
	      Power_CHT_Timer = 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;

	  uint16_t val;
	  val = __HAL_TIM_GET_COMPARE(&htim2, TIM_CHANNEL_1);
	  PutCharSerial (&uc2, (val & 31) + 32);

	  // send the observations
	  ProcessRPM (0);
	  ProcessCHT (0);
	  ProcessCHT (1);
	  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};

  /** Configure the main internal regulator output voltage
  */
  __HAL_PWR_VOLTAGESCALING_CONFIG(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.PLLMUL = RCC_PLL_MUL6;
  RCC_OscInitStruct.PLL.PLLDIV = RCC_PLL_DIV3;
  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_1) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief ADC Initialization Function
  * @param None
  * @retval None
  */
static void MX_ADC_Init(void)
{

  /* USER CODE BEGIN ADC_Init 0 */

  /* USER CODE END ADC_Init 0 */

  ADC_ChannelConfTypeDef sConfig = {0};

  /* USER CODE BEGIN ADC_Init 1 */

  /* USER CODE END ADC_Init 1 */
  /** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
  */
  hadc.Instance = ADC1;
  hadc.Init.ClockPrescaler = ADC_CLOCK_ASYNC_DIV1;
  hadc.Init.Resolution = ADC_RESOLUTION_12B;
  hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT;
  hadc.Init.ScanConvMode = ADC_SCAN_ENABLE;
  hadc.Init.EOCSelection = ADC_EOC_SEQ_CONV;
  hadc.Init.LowPowerAutoWait = ADC_AUTOWAIT_DISABLE;
  hadc.Init.LowPowerAutoPowerOff = ADC_AUTOPOWEROFF_DISABLE;
  hadc.Init.ChannelsBank = ADC_CHANNELS_BANK_A;
  hadc.Init.ContinuousConvMode = DISABLE;
  hadc.Init.NbrOfConversion = 6;
  hadc.Init.DiscontinuousConvMode = DISABLE;
  hadc.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T3_TRGO;
  hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_RISING;
  hadc.Init.DMAContinuousRequests = ENABLE;
  if (HAL_ADC_Init(&hadc) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
  */
  sConfig.Channel = ADC_CHANNEL_10;
  sConfig.Rank = ADC_REGULAR_RANK_1;
  sConfig.SamplingTime = ADC_SAMPLETIME_384CYCLES;
  if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
  */
  sConfig.Channel = ADC_CHANNEL_11;
  sConfig.Rank = ADC_REGULAR_RANK_2;
  if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
  */
  sConfig.Channel = ADC_CHANNEL_12;
  sConfig.Rank = ADC_REGULAR_RANK_3;
  if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
  */
  sConfig.Channel = ADC_CHANNEL_13;
  sConfig.Rank = ADC_REGULAR_RANK_4;
  if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
  */
  sConfig.Channel = ADC_CHANNEL_TEMPSENSOR;
  sConfig.Rank = ADC_REGULAR_RANK_5;
  if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /** Configure for the selected ADC regular channel its corresponding rank in the sequencer and its sample time.
  */
  sConfig.Channel = ADC_CHANNEL_VREFINT;
  sConfig.Rank = ADC_REGULAR_RANK_6;
  if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN ADC_Init 2 */

  /* USER CODE END ADC_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_16;
  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 = 320;
  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_BOTHEDGE;
  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();
  }
  /* 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 = 320;
  htim3.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim3.Init.Period = 100;
  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 = 99;
  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 TIM6 Initialization Function
  * @param None
  * @retval None
  */
static void MX_TIM6_Init(void)
{

  /* USER CODE BEGIN TIM6_Init 0 */

  /* USER CODE END TIM6_Init 0 */

  TIM_MasterConfigTypeDef sMasterConfig = {0};

  /* USER CODE BEGIN TIM6_Init 1 */

  /* USER CODE END TIM6_Init 1 */
  htim6.Instance = TIM6;
  htim6.Init.Prescaler = 320;
  htim6.Init.CounterMode = TIM_COUNTERMODE_UP;
  htim6.Init.Period = 9999;
  htim6.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
  if (HAL_TIM_Base_Init(&htim6) != HAL_OK)
  {
    Error_Handler();
  }
  sMasterConfig.MasterOutputTrigger = TIM_TRGO_UPDATE;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim6, &sMasterConfig) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN TIM6_Init 2 */

  /* USER CODE END TIM6_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 */

}

/**
  * @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;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_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_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();
  __HAL_RCC_GPIOD_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(SPI_NSS1_GPIO_Port, SPI_NSS1_Pin, GPIO_PIN_SET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(SPI_CD_GPIO_Port, SPI_CD_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(GPIOB, SPI_RESET_Pin|SPI_NS_Temp2_Pin|ENA_AUX_5V_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(SPI_NS_Temp_GPIO_Port, SPI_NS_Temp_Pin, GPIO_PIN_SET);

  /*Configure GPIO pins : PC13 PC14 PC15 PC6
                           PC7 PC8 PC9 PC11
                           PC12 */
  GPIO_InitStruct.Pin = GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15|GPIO_PIN_6
                          |GPIO_PIN_7|GPIO_PIN_8|GPIO_PIN_9|GPIO_PIN_11
                          |GPIO_PIN_12;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

  /*Configure GPIO pins : PH0 PH1 */
  GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOH, &GPIO_InitStruct);

  /*Configure GPIO pins : PA0 PA1 PA8 PA11
                           PA12 */
  GPIO_InitStruct.Pin = GPIO_PIN_0|GPIO_PIN_1|GPIO_PIN_8|GPIO_PIN_11
                          |GPIO_PIN_12;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

  /*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_VERY_HIGH;
  HAL_GPIO_Init(LED_Blink_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pins : SPI_NSS1_Pin SPI_CD_Pin */
  GPIO_InitStruct.Pin = SPI_NSS1_Pin|SPI_CD_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);

  /*Configure GPIO pins : SPI_RESET_Pin SPI_NS_Temp_Pin SPI_NS_Temp2_Pin ENA_AUX_5V_Pin */
  GPIO_InitStruct.Pin = SPI_RESET_Pin|SPI_NS_Temp_Pin|SPI_NS_Temp2_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 pins : PB11 PB12 PB13 PB14
                           PB15 PB3 PB4 PB5
                           PB6 PB7 PB8 PB9 */
  GPIO_InitStruct.Pin = GPIO_PIN_11|GPIO_PIN_12|GPIO_PIN_13|GPIO_PIN_14
                          |GPIO_PIN_15|GPIO_PIN_3|GPIO_PIN_4|GPIO_PIN_5
                          |GPIO_PIN_6|GPIO_PIN_7|GPIO_PIN_8|GPIO_PIN_9;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  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);

  /*Configure GPIO pin : PD2 */
  GPIO_InitStruct.Pin = GPIO_PIN_2;
  GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(GPIOD, &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,
	 ex: 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****/