text: /* 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 Ultimate Liberty license
    * SLA0044, the "License"; You may not use this file except in compliance with
    * the License. You may obtain a copy of the License at:
    *                             www.st.com/SLA0044
    *
    ******************************************************************************
    */
  /* USER CODE END Header */
  /* Includes ------------------------------------------------------------------*/
  #include "main.h"
  #include "motorcontrol.h"
  
  /* Private includes ----------------------------------------------------------*/
  /* USER CODE BEGIN Includes */
  
  /* USER CODE END Includes */
  
  /* Private typedef -----------------------------------------------------------*/
  /* USER CODE BEGIN PTD */
  
  /* USER CODE END PTD */
  
  /* Private define ------------------------------------------------------------*/
  /* USER CODE BEGIN PD */
  Q_DEFINE_THIS_MODULE(Module_main)
  /* USER CODE END PD */
  
  /* Private macro -------------------------------------------------------------*/
  /* USER CODE BEGIN PM */
  
  /* USER CODE END PM */
  
  /* Private variables ---------------------------------------------------------*/
  ADC_HandleTypeDef hadc1;
  ADC_HandleTypeDef hadc2;
  
  CAN_HandleTypeDef hcan1;
  
  SPI_HandleTypeDef hspi2;
  SPI_HandleTypeDef hspi3;
  DMA_HandleTypeDef hdma_spi2_tx;
  DMA_HandleTypeDef hdma_spi3_tx;
  
  TIM_HandleTypeDef htim1;
  TIM_HandleTypeDef htim2;
  
  UART_HandleTypeDef huart2;
  
  /* USER CODE BEGIN PV */
  
  /* 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_ADC2_Init(void);
  static void MX_TIM1_Init(void);
  static void MX_TIM2_Init(void);
  static void MX_USART2_UART_Init(void);
  static void MX_CAN1_Init(void);
  static void MX_SPI3_Init(void);
  static void MX_SPI2_Init(void);
  static void MX_NVIC_Init(void);
  /* USER CODE BEGIN PFP */
  
  /* USER CODE END PFP */
  
  /* Private user code ---------------------------------------------------------*/
  /* USER CODE BEGIN 0 */
  void onSPI3DMACplt(struct __DMA_HandleTypeDef* hdma) {
    GREEN_OFF();
  }
  void onSPI3DMAError(struct __DMA_HandleTypeDef* hdma) {
    GREEN_OFF();
  }
  
  /* 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_ADC2_Init();
    MX_TIM1_Init();
    MX_TIM2_Init();
    MX_USART2_UART_Init();
    MX_MotorControl_Init();
    MX_CAN1_Init();
    MX_SPI3_Init();
    MX_SPI2_Init();
  
    /* Initialize interrupts */
    MX_NVIC_Init();
    /* USER CODE BEGIN 2 */
    SPI_TRACE();
    /* USER CODE END 2 */
  
    /* Infinite loop */
    /* USER CODE BEGIN WHILE */
    while (1)
    {
      /* 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_RCC_PWR_CLK_ENABLE();
    __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_HSE;
    RCC_OscInitStruct.HSEState = RCC_HSE_ON;
    RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
    RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
    RCC_OscInitStruct.PLL.PLLM = 4;
    RCC_OscInitStruct.PLL.PLLN = 180;
    RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
    RCC_OscInitStruct.PLL.PLLQ = 2;
    RCC_OscInitStruct.PLL.PLLR = 2;
    if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
    {
      Error_Handler();
    }
    /** Activate the Over-Drive mode
    */
    if (HAL_PWREx_EnableOverDrive() != 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_DIV4;
    RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
  
    if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
    {
      Error_Handler();
    }
  }
  
  /**
    * @brief NVIC Configuration.
    * @retval None
    */
  static void MX_NVIC_Init(void)
  {
    /* ADC_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(ADC_IRQn, 2, 0);
    HAL_NVIC_EnableIRQ(ADC_IRQn);
    /* TIM1_UP_TIM10_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(TIM1_UP_TIM10_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(TIM1_UP_TIM10_IRQn);
    /* TIM1_BRK_TIM9_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(TIM1_BRK_TIM9_IRQn, 4, 1);
    HAL_NVIC_EnableIRQ(TIM1_BRK_TIM9_IRQn);
    /* TIM2_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(TIM2_IRQn, 3, 0);
    HAL_NVIC_EnableIRQ(TIM2_IRQn);
    /* USART2_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(USART2_IRQn, 3, 1);
    HAL_NVIC_EnableIRQ(USART2_IRQn);
  }
  
  /**
    * @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_InjectionConfTypeDef sConfigInjected = {0};
    ADC_ChannelConfTypeDef sConfig = {0};
  
    /* USER CODE BEGIN ADC1_Init 1 */
  
    /* USER CODE END ADC1_Init 1 */
    /** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
    */
    hadc1.Instance = ADC1;
    hadc1.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
    hadc1.Init.Resolution = ADC_RESOLUTION_12B;
    hadc1.Init.ScanConvMode = ENABLE;
    hadc1.Init.ContinuousConvMode = DISABLE;
    hadc1.Init.DiscontinuousConvMode = DISABLE;
    hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
    hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
    hadc1.Init.DataAlign = ADC_DATAALIGN_LEFT;
    hadc1.Init.NbrOfConversion = 2;
    hadc1.Init.DMAContinuousRequests = DISABLE;
    hadc1.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
    if (HAL_ADC_Init(&hadc1) != HAL_OK)
    {
      Error_Handler();
    }
    /** Configures for the selected ADC injected channel its corresponding rank in the sequencer and its sample time
    */
    sConfigInjected.InjectedChannel = ADC_CHANNEL_0;
    sConfigInjected.InjectedRank = 1;
    sConfigInjected.InjectedNbrOfConversion = 3;
    sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_15CYCLES;
    sConfigInjected.ExternalTrigInjecConvEdge = ADC_EXTERNALTRIGINJECCONVEDGE_RISING;
    sConfigInjected.ExternalTrigInjecConv = ADC_EXTERNALTRIGINJECCONV_T1_CC4;
    sConfigInjected.AutoInjectedConv = DISABLE;
    sConfigInjected.InjectedDiscontinuousConvMode = ENABLE;
    sConfigInjected.InjectedOffset = 0;
    if (HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected) != HAL_OK)
    {
      Error_Handler();
    }
    /** Configures for the selected ADC injected channel its corresponding rank in the sequencer and its sample time
    */
    sConfigInjected.InjectedChannel = ADC_CHANNEL_11;
    sConfigInjected.InjectedRank = 2;
    if (HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected) != HAL_OK)
    {
      Error_Handler();
    }
    /** Configures for the selected ADC injected channel its corresponding rank in the sequencer and its sample time
    */
    sConfigInjected.InjectedChannel = ADC_CHANNEL_10;
    sConfigInjected.InjectedRank = 3;
    if (HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected) != 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_1;
    sConfig.Rank = 1;
    sConfig.SamplingTime = ADC_SAMPLETIME_28CYCLES;
    sConfig.Offset = 0;
  
    if (HAL_ADC_ConfigChannel(&hadc1, &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 = 2;
    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_InjectionConfTypeDef sConfigInjected = {0};
    ADC_ChannelConfTypeDef sConfig = {0};
  
    /* USER CODE BEGIN ADC2_Init 1 */
  
    /* USER CODE END ADC2_Init 1 */
    /** Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion)
    */
    hadc2.Instance = ADC2;
    hadc2.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4;
    hadc2.Init.Resolution = ADC_RESOLUTION_12B;
    hadc2.Init.ScanConvMode = ENABLE;
    hadc2.Init.ContinuousConvMode = DISABLE;
    hadc2.Init.DiscontinuousConvMode = DISABLE;
    hadc2.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE;
    hadc2.Init.ExternalTrigConv = ADC_SOFTWARE_START;
    hadc2.Init.DataAlign = ADC_DATAALIGN_LEFT;
    hadc2.Init.NbrOfConversion = 1;
    hadc2.Init.DMAContinuousRequests = DISABLE;
    hadc2.Init.EOCSelection = ADC_EOC_SINGLE_CONV;
    if (HAL_ADC_Init(&hadc2) != HAL_OK)
    {
      Error_Handler();
    }
    /** Configures for the selected ADC injected channel its corresponding rank in the sequencer and its sample time
    */
    sConfigInjected.InjectedChannel = ADC_CHANNEL_0;
    sConfigInjected.InjectedRank = 1;
    sConfigInjected.InjectedNbrOfConversion = 3;
    sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_15CYCLES;
    sConfigInjected.ExternalTrigInjecConvEdge = ADC_EXTERNALTRIGINJECCONVEDGE_RISING;
    sConfigInjected.ExternalTrigInjecConv = ADC_EXTERNALTRIGINJECCONV_T1_CC4;
    sConfigInjected.AutoInjectedConv = DISABLE;
    sConfigInjected.InjectedDiscontinuousConvMode = ENABLE;
    sConfigInjected.InjectedOffset = 0;
    if (HAL_ADCEx_InjectedConfigChannel(&hadc2, &sConfigInjected) != HAL_OK)
    {
      Error_Handler();
    }
    /** Configures for the selected ADC injected channel its corresponding rank in the sequencer and its sample time
    */
    sConfigInjected.InjectedChannel = ADC_CHANNEL_11;
    sConfigInjected.InjectedRank = 2;
    if (HAL_ADCEx_InjectedConfigChannel(&hadc2, &sConfigInjected) != HAL_OK)
    {
      Error_Handler();
    }
    /** Configures for the selected ADC injected channel its corresponding rank in the sequencer and its sample time
    */
    sConfigInjected.InjectedChannel = ADC_CHANNEL_10;
    sConfigInjected.InjectedRank = 3;
    if (HAL_ADCEx_InjectedConfigChannel(&hadc2, &sConfigInjected) != 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_0;
    sConfig.Rank = 1;
    sConfig.SamplingTime = ADC_SAMPLETIME_15CYCLES;
    if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
    {
      Error_Handler();
    }
    /* USER CODE BEGIN ADC2_Init 2 */
  
    /* USER CODE END ADC2_Init 2 */
  
  }
  
  /**
    * @brief CAN1 Initialization Function
    * @param None
    * @retval None
    */
  static void MX_CAN1_Init(void)
  {
  
    /* USER CODE BEGIN CAN1_Init 0 */
  
    /* USER CODE END CAN1_Init 0 */
  
    /* USER CODE BEGIN CAN1_Init 1 */
  
    /* USER CODE END CAN1_Init 1 */
    hcan1.Instance = CAN1;
    hcan1.Init.Prescaler = 5;
    hcan1.Init.Mode = CAN_MODE_NORMAL;
    hcan1.Init.SyncJumpWidth = CAN_SJW_3TQ;
    hcan1.Init.TimeSeg1 = CAN_BS1_3TQ;
    hcan1.Init.TimeSeg2 = CAN_BS2_3TQ;
    hcan1.Init.TimeTriggeredMode = DISABLE;
    hcan1.Init.AutoBusOff = DISABLE;
    hcan1.Init.AutoWakeUp = DISABLE;
    hcan1.Init.AutoRetransmission = ENABLE;
    hcan1.Init.ReceiveFifoLocked = DISABLE;
    hcan1.Init.TransmitFifoPriority = DISABLE;
    if (HAL_CAN_Init(&hcan1) != HAL_OK)
    {
      Error_Handler();
    }
    /* USER CODE BEGIN CAN1_Init 2 */
  
    /* USER CODE END CAN1_Init 2 */
  
  }
  
  /**
    * @brief SPI2 Initialization Function
    * @param None
    * @retval None
    */
  static void MX_SPI2_Init(void)
  {
  
    /* USER CODE BEGIN SPI2_Init 0 */
  
    /* USER CODE END SPI2_Init 0 */
  
    /* USER CODE BEGIN SPI2_Init 1 */
  
    /* USER CODE END SPI2_Init 1 */
    /* SPI2 parameter configuration*/
    hspi2.Instance = SPI2;
    hspi2.Init.Mode = SPI_MODE_MASTER;
    hspi2.Init.Direction = SPI_DIRECTION_2LINES;
    hspi2.Init.DataSize = SPI_DATASIZE_8BIT;
    hspi2.Init.CLKPolarity = SPI_POLARITY_LOW;
    hspi2.Init.CLKPhase = SPI_PHASE_1EDGE;
    hspi2.Init.NSS = SPI_NSS_SOFT;
    hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
    hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
    hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
    hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
    hspi2.Init.CRCPolynomial = 10;
    if (HAL_SPI_Init(&hspi2) != HAL_OK)
    {
      Error_Handler();
    }
    /* USER CODE BEGIN SPI2_Init 2 */
  
    /* USER CODE END SPI2_Init 2 */
  
  }
  
  /**
    * @brief SPI3 Initialization Function
    * @param None
    * @retval None
    */
  static void MX_SPI3_Init(void)
  {
  
    /* USER CODE BEGIN SPI3_Init 0 */
  
    /* USER CODE END SPI3_Init 0 */
  
    /* USER CODE BEGIN SPI3_Init 1 */
  
    /* USER CODE END SPI3_Init 1 */
    /* SPI3 parameter configuration*/
    hspi3.Instance = SPI3;
    hspi3.Init.Mode = SPI_MODE_MASTER;
    hspi3.Init.Direction = SPI_DIRECTION_2LINES;
    hspi3.Init.DataSize = SPI_DATASIZE_16BIT;
    hspi3.Init.CLKPolarity = SPI_POLARITY_LOW;
    hspi3.Init.CLKPhase = SPI_PHASE_1EDGE;
    hspi3.Init.NSS = SPI_NSS_SOFT;
    hspi3.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_2;
    hspi3.Init.FirstBit = SPI_FIRSTBIT_MSB;
    hspi3.Init.TIMode = SPI_TIMODE_DISABLE;
    hspi3.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
    hspi3.Init.CRCPolynomial = 10;
    if (HAL_SPI_Init(&hspi3) != HAL_OK)
    {
      Error_Handler();
    }
    /* USER CODE BEGIN SPI3_Init 2 */
    // HAL is not calling this back
    hdma_spi3_tx.XferCpltCallback = onSPI3DMACplt;
    hdma_spi3_tx.XferErrorCallback = onSPI3DMAError;
    /* USER CODE END SPI3_Init 2 */
  
  }
  
  /**
    * @brief TIM1 Initialization Function
    * @param None
    * @retval None
    */
  static void MX_TIM1_Init(void)
  {
  
    /* USER CODE BEGIN TIM1_Init 0 */
  
    /* USER CODE END TIM1_Init 0 */
  
    TIM_SlaveConfigTypeDef sSlaveConfig = {0};
    TIM_MasterConfigTypeDef sMasterConfig = {0};
    TIM_OC_InitTypeDef sConfigOC = {0};
    TIM_BreakDeadTimeConfigTypeDef sBreakDeadTimeConfig = {0};
  
    /* USER CODE BEGIN TIM1_Init 1 */
  
    /* USER CODE END TIM1_Init 1 */
    htim1.Instance = TIM1;
    htim1.Init.Prescaler = ((TIM_CLOCK_DIVIDER) - 1);
    htim1.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED1;
    htim1.Init.Period = ((PWM_PERIOD_CYCLES) / 2);
    htim1.Init.ClockDivision = TIM_CLOCKDIVISION_DIV2;
    htim1.Init.RepetitionCounter = (REP_COUNTER);
    htim1.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
    if (HAL_TIM_Base_Init(&htim1) != HAL_OK)
    {
      Error_Handler();
    }
    if (HAL_TIM_PWM_Init(&htim1) != HAL_OK)
    {
      Error_Handler();
    }
    sSlaveConfig.SlaveMode = TIM_SLAVEMODE_TRIGGER;
    sSlaveConfig.InputTrigger = TIM_TS_ITR1;
    if (HAL_TIM_SlaveConfigSynchro(&htim1, &sSlaveConfig) != HAL_OK)
    {
      Error_Handler();
    }
    sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
    sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
    if (HAL_TIMEx_MasterConfigSynchronization(&htim1, &sMasterConfig) != HAL_OK)
    {
      Error_Handler();
    }
    sConfigOC.OCMode = TIM_OCMODE_PWM1;
    sConfigOC.Pulse = 0;
    sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
    sConfigOC.OCNPolarity = TIM_OCNPOLARITY_LOW;
    sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
    sConfigOC.OCIdleState = TIM_OCIDLESTATE_RESET;
    sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_SET;
    if (HAL_TIM_PWM_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
    {
      Error_Handler();
    }
    if (HAL_TIM_PWM_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
    {
      Error_Handler();
    }
    if (HAL_TIM_PWM_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_3) != HAL_OK)
    {
      Error_Handler();
    }
    sConfigOC.OCMode = TIM_OCMODE_PWM2;
    sConfigOC.Pulse = (((PWM_PERIOD_CYCLES) / 2) - (HTMIN));
    sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
    if (HAL_TIM_PWM_ConfigChannel(&htim1, &sConfigOC, TIM_CHANNEL_4) != HAL_OK)
    {
      Error_Handler();
    }
    sBreakDeadTimeConfig.OffStateRunMode = TIM_OSSR_ENABLE;
    sBreakDeadTimeConfig.OffStateIDLEMode = TIM_OSSI_ENABLE;
    sBreakDeadTimeConfig.LockLevel = TIM_LOCKLEVEL_1;
    sBreakDeadTimeConfig.DeadTime = ((DEAD_TIME_COUNTS) / 2);
    sBreakDeadTimeConfig.BreakState = TIM_BREAK_ENABLE;
    sBreakDeadTimeConfig.BreakPolarity = TIM_BREAKPOLARITY_LOW;
    sBreakDeadTimeConfig.AutomaticOutput = TIM_AUTOMATICOUTPUT_DISABLE;
    if (HAL_TIMEx_ConfigBreakDeadTime(&htim1, &sBreakDeadTimeConfig) != HAL_OK)
    {
      Error_Handler();
    }
    /* USER CODE BEGIN TIM1_Init 2 */
  
    /* USER CODE END TIM1_Init 2 */
    HAL_TIM_MspPostInit(&htim1);
  
  }
  
  /**
    * @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_HallSensor_InitTypeDef sConfig = {0};
    TIM_MasterConfigTypeDef sMasterConfig = {0};
  
    /* USER CODE BEGIN TIM2_Init 1 */
  
    /* USER CODE END TIM2_Init 1 */
    htim2.Instance = TIM2;
    htim2.Init.Prescaler = 0;
    htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
    htim2.Init.Period = M1_HALL_TIM_PERIOD;
    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();
    }
    sConfig.IC1Polarity = TIM_ICPOLARITY_RISING;
    sConfig.IC1Prescaler = TIM_ICPSC_DIV1;
    sConfig.IC1Filter = M1_HALL_IC_FILTER;
    sConfig.Commutation_Delay = 0;
    if (HAL_TIMEx_HallSensor_Init(&htim2, &sConfig) != HAL_OK)
    {
      Error_Handler();
    }
    sMasterConfig.MasterOutputTrigger = TIM_TRGO_OC2REF;
    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 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_Stream4_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(DMA1_Stream4_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(DMA1_Stream4_IRQn);
    /* DMA1_Stream5_IRQn interrupt configuration */
    HAL_NVIC_SetPriority(DMA1_Stream5_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(DMA1_Stream5_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_GPIOH_CLK_ENABLE();
    __HAL_RCC_GPIOC_CLK_ENABLE();
    __HAL_RCC_GPIOA_CLK_ENABLE();
    __HAL_RCC_GPIOB_CLK_ENABLE();
  
    /*Configure GPIO pin Output Level */
    HAL_GPIO_WritePin(GPIOB, RED_Pin|GREEN_Pin, GPIO_PIN_RESET);
  
    /*Configure GPIO pins : RED_Pin GREEN_Pin */
    GPIO_InitStruct.Pin = RED_Pin|GREEN_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);
  
  }
  
  /* USER CODE BEGIN 4 */
  #define SPI_LOG_WORD_WIDTH 16
  #include <stdarg.h>
  struct LogItem {
    uint8_t n;
    uint8_t module;
    uint16_t loc;
    uint16_t arg[8];
  } __attribute__((aligned(4)));
  
  #ifdef BB_SPI_CLK_Pin // bit-bang SPI
  void BBSpiMode0_write_only(uint16_t wb) {
    uint32_t msk = 1UL << (SPI_LOG_WORD_WIDTH-1);
    do {
      BB_SPI_CLK_GPIO_Port->ODR &= ~BB_SPI_CLK_Pin; // deassert CLK
      if(wb & msk) { // set MOSI
        BB_SPI_MOSI_GPIO_Port->ODR |=  BB_SPI_MOSI_Pin;
      } else {
        BB_SPI_MOSI_GPIO_Port->ODR &= ~BB_SPI_MOSI_Pin;
      }
      BB_SPI_CLK_GPIO_Port->ODR |= BB_SPI_CLK_Pin; // assert CLK
      // The slave will read the MOSI pin during the transition
      //BB_SPI_CLK_GPIO_Port->ODR &= ~BB_SPI_CLK_Pin; // deassert CLK
    } while(msk>>=1);
    BB_SPI_CLK_GPIO_Port->ODR &= ~BB_SPI_CLK_Pin; // deassert CLK
  }
  #endif
  
  void spilog(uint8_t module, uint16_t loc, const char* fmt, ...) {
    struct LogItem log;
    uint8_t n = 0;
    log.module = module;
    log.loc = loc;
  
    if (fmt && *fmt) {
      va_list args;
      va_start(args, fmt);
      for ( ; *fmt && n < Q_DIM(log.arg); ++fmt, ++n) {
        switch (*fmt) {
  	case 'h': // short
  	  *((int16_t*)&log.arg[n]) = (int16_t)va_arg(args, int);
  	  break;
  
  	case '2': // unsigned short (should be hu but I got lazy)
  	  log.arg[n] = (uint16_t)va_arg(args, unsigned);
  	  break;
  
  	case 'd': { // native (32-bit) int
  	  int32_t i = va_arg(args, int);
  	  // show the top 16-bit
  	  *((int16_t*)&log.arg[n]) = i >> 16;
  	  if (++n >= Q_DIM(log.arg)) {
  	      --n; // protect against trashing buffer
  	      break;
  	  }
  	  // then show the bottom 16-bit
  	  *((int16_t*)&log.arg[n]) = i & 0xFFFF;
  	}   break;
  
  	case '4': { // native (32-bit) unsigned
  	  uint32_t i = va_arg(args, unsigned);
  	  log.arg[n] = i >> 16;
  	  if (++n >= Q_DIM(log.arg)) {
  	      --n; // protect against trashing buffer
  	      break;
  	  }
  	  log.arg[n] = i & 0xFFFF;
  	}   break;
  
  	default: break;
        }
      }
      va_end(args);
    }
    log.n = n;
  
  #ifdef BB_SPI_CLK_Pin // bit-bang SPI
    // write out the MOSI now
    const uint16_t* p = (const uint16_t*)&log;
    BBSpiMode0_write_only(*p); // write header
    BBSpiMode0_write_only(*++p);
    for (unsigned i=0; i < log.n; ++i) { //write arguments
      BBSpiMode0_write_only(*++p);
    }
  #else // use SPI DMA
  //GREEN_ON();
    if (HAL_SPI_Transmit_DMA(&hspi3, (uint8_t*)&log, 2 + log.n) != HAL_OK) {
      (void)hspi3.State;
    }
  //while (hspi3.State != HAL_SPI_STATE_READY) {}
  //GREEN_OFF();
  #endif
  }
  
  /* 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****/
  