Guest User

3_Phase_Center_Aligned_PWM

a guest
Sep 8th, 2017
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 14.33 KB | None | 0 0
  1. /**
  2.   ******************************************************************************
  3.   * @file    TIM/TIM_TimeBase/Src/main.c
  4.   * @author  MCD Application Team
  5.   * @version V1.2.7
  6.   * @date    17-February-2017
  7.   * @brief   This sample code shows how to use STM32F4xx TIM HAL API to generate
  8.   *          4 signals in PWM.
  9.   ******************************************************************************
  10.   * @attention
  11.   *
  12.   * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2>
  13.   *
  14.   * Redistribution and use in source and binary forms, with or without modification,
  15.   * are permitted provided that the following conditions are met:
  16.   *   1. Redistributions of source code must retain the above copyright notice,
  17.   *      this list of conditions and the following disclaimer.
  18.   *   2. Redistributions in binary form must reproduce the above copyright notice,
  19.   *      this list of conditions and the following disclaimer in the documentation
  20.   *      and/or other materials provided with the distribution.
  21.   *   3. Neither the name of STMicroelectronics nor the names of its contributors
  22.   *      may be used to endorse or promote products derived from this software
  23.   *      without specific prior written permission.
  24.   *
  25.   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  26.   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  27.   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  28.   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  29.   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  30.   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  31.   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  32.   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  33.   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  34.   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  35.   *
  36.   ******************************************************************************
  37.   */
  38.  
  39. /* Includes ------------------------------------------------------------------*/
  40. #include "main.h"
  41.  
  42. /** @addtogroup STM32F4xx_HAL_Examples
  43.   * @{
  44.   */
  45.  
  46. /** @addtogroup TIM_TimeBase
  47.   * @{
  48.   */
  49.  
  50. /* Private typedef -----------------------------------------------------------*/
  51. /* Private define ------------------------------------------------------------*/
  52. /* Private macro -------------------------------------------------------------*/
  53. /* Private variables ---------------------------------------------------------*/
  54. TIM_HandleTypeDef TimHandle;
  55. TIM_OC_InitTypeDef  TIM_OCInitStructure;
  56. TIM_BreakDeadTimeConfigTypeDef TIM_BDTRInitStructure;
  57. TIM_ClockConfigTypeDef sClockSourceConfig;
  58.  
  59. uint32_t timePeriod = 0;
  60. uint32_t duty1, duty2, duty3 = 0;
  61.  
  62. /* Private function prototypes -----------------------------------------------*/
  63. static void SystemClock_Config(void);
  64. static void Error_Handler(void);
  65. static void TIM_Config(void);
  66. static void PWM_SetDutyCycle(TIM_HandleTypeDef *htim, uint32_t duty, uint32_t channel);
  67.  
  68. /* Private functions ---------------------------------------------------------*/
  69.  
  70. /**
  71.   * @brief  Main program
  72.   * @param  None
  73.   * @retval None
  74.   */
  75. int main(void)
  76. {
  77.  
  78.   /* STM32F4xx HAL library initialization:
  79.        - Configure the Flash prefetch, instruction and Data caches
  80.        - Configure the Systick to generate an interrupt each 1 msec
  81.        - Set NVIC Group Priority to 4
  82.        - Global MSP (MCU Support Package) initialization
  83.      */
  84.   if(HAL_Init()!= HAL_OK)
  85.   {
  86.     /* Start Conversation Error */
  87.     Error_Handler();
  88.   }
  89.  
  90.   /* Configure the system clock to 168 MHz */
  91.   SystemClock_Config();
  92.  
  93.   /* Configure LED3 and LED4 */
  94.   BSP_LED_Init(LED3);
  95.   BSP_LED_Init(LED4);
  96.  
  97.   /* Configure the Timer-1 output through respective GPIO pins */
  98.   TIM_Config();
  99.  
  100.   /*##-1- Configure the TIM peripheral #######################################*/
  101.   /* -----------------------------------------------------------------------
  102.     In this example TIM3 input clock (TIM3CLK) is set to 2 * APB1 clock (PCLK1),
  103.     since APB1 prescaler is different from 1.  
  104.       TIM3CLK = 2 * PCLK1  
  105.       PCLK1 = HCLK / 4
  106.       => TIM3CLK = HCLK / 2 = SystemCoreClock /2
  107.     To get TIM3 counter clock at 10 KHz, the Prescaler is computed as following:
  108.     Prescaler = (TIM3CLK / TIM3 counter clock) - 1
  109.     Prescaler = ((SystemCoreClock /2) /10 KHz) - 1
  110.        
  111.     Note:
  112.      SystemCoreClock variable holds HCLK frequency and is defined in system_stm32f4xx.c file.
  113.      Each time the core clock (HCLK) changes, user had to update SystemCoreClock
  114.      variable value. Otherwise, any configuration based on this variable will be incorrect.
  115.      This variable is updated in three ways:
  116.       1) by calling CMSIS function SystemCoreClockUpdate()
  117.       2) by calling HAL API function HAL_RCC_GetSysClockFreq()
  118.       3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency  
  119.   ----------------------------------------------------------------------- */  
  120.  
  121.   /* Compute the prescaler value to have TIM3 counter clock equal to 10 KHz */
  122.   timePeriod = (uint32_t) ((SystemCoreClock /2) / 10000) - 1;
  123.   /* Compute CCR1 value to generate a duty cycle at 50% for channel 1 */
  124.   duty1 = (uint32_t) (((uint32_t) 5 * (timePeriod - 1)) / 10);
  125.  
  126.   /* Compute CCR2 value to generate a duty cycle at 25%  for channel 2 */
  127.   duty2 = (uint32_t) (((uint32_t) 25 * (timePeriod - 1)) / 100);
  128.  
  129.   /* Compute CCR3 value to generate a duty cycle at 12.5%  for channel 3 */
  130.   duty3 = (uint32_t) (((uint32_t) 125 * (timePeriod - 1)) / 1000);
  131.  
  132.  
  133.   /* Set TIMx instance */
  134.   TimHandle.Instance = TIM1;
  135.    
  136.   /* Initialize TIM3 peripheral as follow:
  137.        + Period = 10000 - 1
  138.        + Prescaler = ((SystemCoreClock/2)/10000) - 1
  139.        + ClockDivision = 0
  140.        + Counter direction = Up
  141.   */
  142.   TimHandle.Init.Period = timePeriod;
  143.   TimHandle.Init.Prescaler = 0;
  144.   TimHandle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  145.   TimHandle.Init.CounterMode = TIM_COUNTERMODE_CENTERALIGNED1;
  146.   TimHandle.Init.RepetitionCounter = 0;
  147. //  if(HAL_TIM_Base_Init(&TimHandle) != HAL_OK)
  148. //  {
  149. //    /* Initialization Error */
  150. //    Error_Handler();
  151. //  }
  152.  
  153. //  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  154. //  HAL_TIM_ConfigClockSource(&TimHandle, &sClockSourceConfig);
  155.  
  156.   HAL_TIM_PWM_Init(&TimHandle);
  157.  
  158.   /* Channel 1, 2 and 3 Configuration in PWM mode */
  159.   TIM_OCInitStructure.OCMode = TIM_OCMODE_PWM2;
  160.   TIM_OCInitStructure.Pulse = duty1;
  161.   TIM_OCInitStructure.OCFastMode = TIM_OCFAST_DISABLE;
  162.   TIM_OCInitStructure.OCPolarity = TIM_OCPOLARITY_LOW;
  163.   TIM_OCInitStructure.OCNPolarity = TIM_OCNPOLARITY_LOW;
  164.   TIM_OCInitStructure.OCIdleState = TIM_OCIDLESTATE_RESET;
  165.   TIM_OCInitStructure.OCNIdleState = TIM_OCNIDLESTATE_RESET;
  166.  
  167.   HAL_TIM_PWM_ConfigChannel(&TimHandle, &TIM_OCInitStructure, TIM_CHANNEL_1);
  168.  
  169.   TIM_OCInitStructure.Pulse = duty2;
  170.   HAL_TIM_PWM_ConfigChannel(&TimHandle, &TIM_OCInitStructure, TIM_CHANNEL_2);
  171.  
  172.   TIM_OCInitStructure.Pulse = duty3;
  173.   HAL_TIM_PWM_ConfigChannel(&TimHandle, &TIM_OCInitStructure, TIM_CHANNEL_3);
  174.  
  175.  
  176.   /* Automatic Output enable, Break, dead time and lock configuration*/
  177.   TIM_BDTRInitStructure.OffStateRunMode = TIM_OSSR_ENABLE;
  178.   TIM_BDTRInitStructure.OffStateIDLEMode = TIM_OSSR_ENABLE;
  179.   TIM_BDTRInitStructure.LockLevel = TIM_LOCKLEVEL_1;
  180.   TIM_BDTRInitStructure.DeadTime = 10;
  181.   TIM_BDTRInitStructure.BreakState = TIM_BREAK_ENABLE;
  182.   TIM_BDTRInitStructure.BreakPolarity = TIM_BREAKPOLARITY_HIGH;
  183.   TIM_BDTRInitStructure.AutomaticOutput = TIM_AUTOMATICOUTPUT_ENABLE;
  184.  
  185.   HAL_TIMEx_ConfigBreakDeadTime(&TimHandle, &TIM_BDTRInitStructure);
  186.  
  187. //  /*##-2- Start the TIM Base generation in interrupt mode ####################*/
  188. //  /* Start Channel1 */
  189. //  if(HAL_TIM_Base_Start_IT(&TimHandle) != HAL_OK)
  190. //  {
  191. //    /* Starting Error */
  192. //    Error_Handler();
  193. //  }
  194.  
  195.   if(HAL_TIM_PWM_Start_IT(&TimHandle, TIM_CHANNEL_1) != HAL_OK)
  196.   {
  197.     /* Starting Error */
  198.     Error_Handler();
  199.   }
  200.  
  201.   if(HAL_TIM_PWM_Start_IT(&TimHandle, TIM_CHANNEL_2) != HAL_OK)
  202.   {
  203.     /* Starting Error */
  204.     Error_Handler();
  205.   }
  206.  
  207.   if(HAL_TIM_PWM_Start_IT(&TimHandle, TIM_CHANNEL_3) != HAL_OK)
  208.   {
  209.     /* Starting Error */
  210.     Error_Handler();
  211.   }
  212.  
  213.   /* Main Output Enable */
  214.   if(HAL_TIMEx_PWMN_Start_IT(&TimHandle, TIM_CHANNEL_1) != HAL_OK)
  215.   {
  216.     /* Starting Error */
  217.     Error_Handler();
  218.   }
  219.  
  220.   if(HAL_TIMEx_PWMN_Start_IT(&TimHandle, TIM_CHANNEL_2) != HAL_OK)
  221.   {
  222.     /* Starting Error */
  223.     Error_Handler();
  224.   }
  225.  
  226.   if(HAL_TIMEx_PWMN_Start_IT(&TimHandle, TIM_CHANNEL_3) != HAL_OK)
  227.   {
  228.     /* Starting Error */
  229.     Error_Handler();
  230.   }
  231.   /* Infinite loop */
  232.   while (1)
  233.   {
  234. //    int i, j;
  235. //
  236. //    for(i = 0; i<=50000; i++);
  237. //
  238. //    PWM_SetDutyCycle(&TimHandle, 50, TIM_CHANNEL_3);
  239.   }
  240. }
  241.  
  242.  
  243. void PWM_SetDutyCycle(TIM_HandleTypeDef *htim, uint32_t duty, uint32_t channel)
  244. {
  245.      switch(channel)
  246.      {
  247.          case TIM_CHANNEL_1: htim->Instance->CCR1 = (uint32_t)((duty * timePeriod) / 100); break;
  248.          case TIM_CHANNEL_2: htim->Instance->CCR2 = (uint32_t)((duty * timePeriod) / 100); break;
  249.          case TIM_CHANNEL_3: htim->Instance->CCR3 = (uint32_t)((duty * timePeriod) / 100); break;
  250.          case TIM_CHANNEL_4: htim->Instance->CCR4 = (uint32_t)((duty * timePeriod) / 100); break;
  251.      }
  252. }
  253.  
  254. /**
  255.   * @brief  Period elapsed callback in non blocking mode
  256.   * @param  htim: TIM handle
  257.   * @retval None
  258.   */
  259. void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim)
  260. {
  261.   BSP_LED_Toggle(LED4);
  262. }
  263.  
  264. /**
  265.   * @brief  This function is executed in case of error occurrence.
  266.   * @param  None
  267.   * @retval None
  268.   */
  269. static void Error_Handler(void)
  270. {
  271.   /* Turn LED3 on */
  272.   BSP_LED_On(LED3);
  273.   while(1)
  274.   {
  275.   }
  276. }
  277.  
  278. /**
  279.   * @brief  Configure the TIM1 Pins.
  280.   * @param  None
  281.   * @retval None
  282.   */
  283. void TIM_Config(void)
  284. {
  285.   GPIO_InitTypeDef GPIO_InitStructure;
  286.  
  287.   /* GPIOA, GPIOB and GPIOE clocks enable */
  288.   //RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA | RCC_AHB1Periph_GPIOB | RCC_AHB1Periph_GPIOE, ENABLE);
  289.   __HAL_RCC_GPIOA_CLK_ENABLE();
  290.   __HAL_RCC_GPIOB_CLK_ENABLE();
  291.   __HAL_RCC_GPIOE_CLK_ENABLE();
  292.   __TIM1_CLK_ENABLE();
  293.  
  294.   /* TIM1 clock enable */
  295.   //RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
  296.  
  297.   /* GPIOA Configuration: Channel 1 and 3 as alternate function push-pull */
  298.   GPIO_InitStructure.Pin = GPIO_PIN_8 | GPIO_PIN_10;
  299.   GPIO_InitStructure.Mode = GPIO_MODE_AF_PP;
  300.   GPIO_InitStructure.Speed = GPIO_SPEED_FAST;
  301.   GPIO_InitStructure.Pull = GPIO_NOPULL;
  302.   GPIO_InitStructure.Alternate = GPIO_AF1_TIM1;
  303.   HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);
  304.  
  305.   /* GPIOA Configuration: Channel 2 as alternate function push-pull */
  306.   GPIO_InitStructure.Pin = GPIO_PIN_11;
  307.   HAL_GPIO_Init(GPIOE, &GPIO_InitStructure);
  308.  
  309.   /* GPIOB Configuration: BKIN, Channel 1N, 2N and 3N as alternate function push-pull */
  310.   GPIO_InitStructure.Pin = GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15;
  311.   HAL_GPIO_Init(GPIOB, &GPIO_InitStructure);
  312. }
  313.  
  314. /**
  315.   * @brief  System Clock Configuration
  316.   *         The system Clock is configured as follow :
  317.   *            System Clock source            = PLL (HSE)
  318.   *            SYSCLK(Hz)                     = 168000000
  319.   *            HCLK(Hz)                       = 168000000
  320.   *            AHB Prescaler                  = 1
  321.   *            APB1 Prescaler                 = 4
  322.   *            APB2 Prescaler                 = 2
  323.   *            HSE Frequency(Hz)              = 8000000
  324.   *            PLL_M                          = 8
  325.   *            PLL_N                          = 336
  326.   *            PLL_P                          = 2
  327.   *            PLL_Q                          = 7
  328.   *            VDD(V)                         = 3.3
  329.   *            Main regulator output voltage  = Scale1 mode
  330.   *            Flash Latency(WS)              = 5
  331.   * @param  None
  332.   * @retval None
  333.   */
  334. static void SystemClock_Config(void)
  335. {
  336.   RCC_ClkInitTypeDef RCC_ClkInitStruct;
  337.   RCC_OscInitTypeDef RCC_OscInitStruct;
  338.  
  339.   /* Enable Power Control clock */
  340.   __HAL_RCC_PWR_CLK_ENABLE();
  341.  
  342.   /* The voltage scaling allows optimizing the power consumption when the device is
  343.      clocked below the maximum system frequency, to update the voltage scaling value
  344.      regarding system frequency refer to product datasheet.  */
  345.   __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  346.  
  347.   /* Enable HSE Oscillator and activate PLL with HSE as source */
  348.   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  349.   RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  350.   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  351.   RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  352.   RCC_OscInitStruct.PLL.PLLM = 8;
  353.   RCC_OscInitStruct.PLL.PLLN = 336;
  354.   RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  355.   RCC_OscInitStruct.PLL.PLLQ = 7;
  356.   if(HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  357.   {
  358.     Error_Handler();
  359.   }
  360.  
  361.   /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2
  362.      clocks dividers */
  363.   RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2);
  364.   RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  365.   RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  366.   RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;  
  367.   RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;  
  368.   if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  369.   {
  370.     Error_Handler();
  371.   }
  372.  
  373.   /* STM32F405x/407x/415x/417x Revision Z devices: prefetch is supported  */
  374.   if (HAL_GetREVID() == 0x1001)
  375.   {
  376.     /* Enable the Flash prefetch */
  377.     __HAL_FLASH_PREFETCH_BUFFER_ENABLE();
  378.   }
  379. }
  380.  
  381.  
  382. #ifdef  USE_FULL_ASSERT
  383.  
  384. /**
  385.   * @brief  Reports the name of the source file and the source line number
  386.   *         where the assert_param error has occurred.
  387.   * @param  file: pointer to the source file name
  388.   * @param  line: assert_param error line source number
  389.   * @retval None
  390.   */
  391. void assert_failed(uint8_t* file, uint32_t line)
  392. {
  393.   /* User can add his own implementation to report the file name and line number,
  394.      ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  395.  
  396.   /* Infinite loop */
  397.   while (1)
  398.   {
  399.   }
  400. }
  401. #endif
  402.  
  403. /**
  404.   * @}
  405.   */
  406.  
  407. /**
  408.   * @}
  409.   */
  410.  
  411. /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
Add Comment
Please, Sign In to add comment