
/**
 ******************************************************************************
 * File Name          : main.c
 * Description        : Main program body
 ******************************************************************************
 *
 * COPYRIGHT(c) 2017 STMicroelectronics
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *   1. Redistributions of source code must retain the above copyright notice,
 *      this list of conditions and the following disclaimer.
 *   2. Redistributions in binary form must reproduce the above copyright notice,
 *      this list of conditions and the following disclaimer in the documentation
 *      and/or other materials provided with the distribution.
 *   3. Neither the name of STMicroelectronics nor the names of its contributors
 *      may be used to endorse or promote products derived from this software
 *      without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 ******************************************************************************
 */
/* Includes ------------------------------------------------------------------*/
#include "stm32l1xx_hal.h"

/* USER CODE BEGIN Includes */
#include "serial.h"
#include "plx.h"
#include "misc.h"
/* USER CODE END Includes */

/* Private variables ---------------------------------------------------------*/
ADC_HandleTypeDef hadc;
DMA_HandleTypeDef hdma_adc;

SPI_HandleTypeDef hspi1;

TIM_HandleTypeDef htim2;
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,
#define BREAKER_MIN (RPM_COUNT_RATE/300)

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
unsigned int RPM_Diff = 0;
unsigned int RPM_Count_Latch = 0;
// accumulators
unsigned int RPM_Pulsecount = 0;
unsigned int RPM_FilteredWidth = 0;

unsigned int Coded_RPM = 0;
unsigned int Coded_CHT = 0;

uint32_t Power_CHT_Timer;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
void Error_Handler(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_USART2_UART_Init(void);
static void MX_USART1_UART_Init(void);

/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/

/* USER CODE END PFP */

/* 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;
	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;
			if (next_count == RPM_SAMPLES)
			{
				next_count = 0;
			}
			if (next_count == RPM_Count_Val)
			{
				break;
			}
			base_time = RPM_Time[RPM_Count_Latch];
			new_time = RPM_Time[next_count];
			RPM_Count_Latch = next_count;
			if (new_time > base_time)
			{
				RPM_Pulsewidth = new_time - base_time; // not wrapped
			}
			else
			{
				RPM_Pulsewidth = new_time - base_time + 65536; // deal with wrapping
			}

			RPM_Diff += RPM_Pulsewidth;
			// need to check if this is a long pulse. If it is, keep the answer
			if (RPM_Pulsewidth > BREAKER_MIN)
			{
				RPM_Pulsecount++; // count one pulse
				RPM_FilteredWidth += RPM_Diff; // add its width to the accumulator
				RPM_Diff = 0; // reset accumulator of all the narrow widths
			}
		}

	}

	if (RPM_Pulsecount > 0)
	{
		// now have time for N pulses in clocks
		// need to scale by 19.55: one unit is 19.55 RPM
		// 1Hz is 60 RPM
		float new_RPM = (30.0 / 19.55 * RPM_Pulsecount * RPM_COUNT_RATE)
				/ (RPM_FilteredWidth) + 0.5;

		Coded_RPM += (new_RPM * Scale - Coded_RPM) / 4;

#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
//

GPIO_PinState CHT_Enable;

uint8_t CHT_Timer[2] =
{ 0, 0 }; // two temperature readings
uint8_t CHT_Observations[2] =
{ 0, 0 };

void ProcessCHT(int instance)
{
	uint8_t buffer[2];
	if (instance > 2)
		return;
	CHT_Timer[instance]++;
	if ((CHT_Enable == GPIO_PIN_SET) && (CHT_Timer[instance] >= 3)) // every 300 milliseconds
	{

		CHT_Timer[instance] = 0;

		uint16_t Pin = (instance == 0) ? SPI_NS_Temp_Pin : SPI_NS_Temp2_Pin;

		HAL_GPIO_WritePin(SPI_NS_Temp_GPIO_Port, Pin, GPIO_PIN_RESET);

		HAL_SPI_Receive(&hspi1, buffer, 2, 2);

		HAL_GPIO_WritePin(SPI_NS_Temp_GPIO_Port, Pin, GPIO_PIN_SET);

		uint16_t obs = (buffer[0] << 8) | buffer[1];

		uint8_t good = (obs & 4) == 0;
		if (good)
		{
			CHT_Observations[instance] = obs >> 5;
		}
		else
		{
			CHT_Observations[instance] = 1024; // signal fail
		}
	}

	plx_sendword(PLX_X_CHT);
	PutCharSerial(&uc1, instance);
	plx_sendword(CHT_Observations[instance]);

}

void EnableCHT(GPIO_PinState state)
{

	CHT_Enable = state;
	HAL_GPIO_WritePin(ENA_AUX_5V_GPIO_Port, ENA_AUX_5V_Pin, state);
}

// 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[6];       // 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 *) 0x1FF8007A; /* ADC reading for temperature sensor at 30 degrees C with Vref = 3000mV */
	uint16_t TS_CAL110 = *(uint16_t *) 0x1FF8007E; /* 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 / 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

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
	reading = (reading) * 1000 / 4.5; // do not assume 0.5 volt offset : reading from 0 to 4.5 instead of 0.5 to 4.5
	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 */

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();

	/* Configure the system clock */
	SystemClock_Config();

	/* Initialize all configured peripherals */
	MX_GPIO_Init();
	MX_DMA_Init();
	MX_ADC_Init();
	MX_SPI1_Init();
	MX_TIM2_Init();
	MX_TIM6_Init();
	MX_USART2_UART_Init();
	MX_USART1_UART_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);

	init_ADC_filter();

	uint32_t Ticks = HAL_GetTick() + 100;
	int CalCounter = 0;

	Power_CHT_Timer = HAL_GetTick() + 10000; /* 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 < 500)
			{
				CalCounter += 100;
			}

			if (CalCounter == 400)
			{
				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)
		{
			EnableCHT(GPIO_PIN_RESET);
			Power_CHT_Timer = HAL_GetTick() + 500;
		}
		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(GPIO_PIN_SET);
				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))
		{
			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 */
}
/** System Clock Configuration
 */
void SystemClock_Config(void)
{

	RCC_OscInitTypeDef RCC_OscInitStruct;
	RCC_ClkInitTypeDef RCC_ClkInitStruct;

	__HAL_RCC_PWR_CLK_ENABLE()
	;

	__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

	RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
	RCC_OscInitStruct.HSIState = RCC_HSI_ON;
	RCC_OscInitStruct.HSICalibrationValue = 16;
	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();
	}

	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();
	}

	HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000);

	HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

	/* SysTick_IRQn interrupt configuration */
	HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}

/* ADC init function */
static void MX_ADC_Init(void)
{

	ADC_ChannelConfTypeDef sConfig;

	/**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_T6_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 = 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 = 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 = 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 = 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 = 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 = 6;
	if (HAL_ADC_ConfigChannel(&hadc, &sConfig) != HAL_OK)
	{
		Error_Handler();
	}

}

/* SPI1 init function */
static void MX_SPI1_Init(void)
{

	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();
	}

}

/* TIM2 init function */
static void MX_TIM2_Init(void)
{

	TIM_ClockConfigTypeDef sClockSourceConfig;
	TIM_MasterConfigTypeDef sMasterConfig;
	TIM_IC_InitTypeDef sConfigIC;

	htim2.Instance = TIM2;
	htim2.Init.Prescaler = 320;
	htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
	htim2.Init.Period = 65535;
	htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
	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 = 0;
	if (HAL_TIM_IC_ConfigChannel(&htim2, &sConfigIC, TIM_CHANNEL_1) != HAL_OK)
	{
		Error_Handler();
	}

}

/* TIM6 init function */
static void MX_TIM6_Init(void)
{

	TIM_MasterConfigTypeDef sMasterConfig;

	htim6.Instance = TIM6;
	htim6.Init.Prescaler = 320;
	htim6.Init.CounterMode = TIM_COUNTERMODE_UP;
	htim6.Init.Period = 9999;
	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();
	}

}

/* USART1 init function */
static void MX_USART1_UART_Init(void)
{

	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();
	}

}

/* USART2 init function */
static void MX_USART2_UART_Init(void)
{

	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();
	}

}

/** 
 * 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);

}

/** Configure pins as 
 * Analog
 * Input
 * Output
 * EVENT_OUT
 * EXTI
 * Free pins are configured automatically as Analog (this feature is enabled through
 * the Code Generation settings)
 */
static void MX_GPIO_Init(void)
{

	GPIO_InitTypeDef GPIO_InitStruct;

	/* 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 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 SPI1CD_Pin */
	GPIO_InitStruct.Pin = SPI_NSS1_Pin | SPI1CD_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);

	/*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(SPI1CD_GPIO_Port, SPI1CD_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);

}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
 * @brief  This function is executed in case of error occurrence.
 * @param  None
 * @retval None
 */
void Error_Handler(void)
{
	/* USER CODE BEGIN Error_Handler */
	/* User can add his own implementation to report the HAL error return state */
	while (1)
	{
	}
	/* USER CODE END Error_Handler */
}

#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

/**
 * @}
 */

/**
 * @}
 */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/