Forum: Mikrocontroller und Digitale Elektronik [STM32F4] PWM mit variablem DutyCycle mit DMA generieren


von tm200014 (Gast)


Lesenswert?

Hallo zusammen!

Ich möchte gerne mit meinem STM32F4 ein PWM-Ausgangssignal erzeugen, 
welches eine feste Frequenz und einen variablen DutyCycle hat. Um den 
Prozessor zu schönen würde ich das gerne mit DMA realisieren.

Ich habe mir mit CubeMX ein entsprechendes Projekt konfiguriert in dem 
ich den Timer 3 Channel 3 für die PWM-Generierung und den DMA1Stream7 in 
Memory to Peripheral mode verwende.

Wenn ich nun mit der Funktion HAL_TIM_PWM_Start() die PWM-Generierung 
starte, funktioniert alles einwandfrei und es wird eine PWM mit etwa 50% 
DutyCycle am Pin PB0 ausgegeben (Period = 52, Pulse = 26).
Nun würde ich gerne ein Array namens buffer erstellen, welches die Werte 
für mein DutyCycle enthält. Hiervon soll bei jedem Überlauf des Timers 
der nächste Wert in das CaptureCompare Register (CCR3) geschrieben 
werden. Wenn jetzt jedoch mit dem Befehl HAL_TIM_PWM_Start_DMA() die 
PWM-Generierung starte, wird am Pin PB0 ein PWM-Signal mit der korrekten 
Frequenz, allerdings nur ein kurzer Spike (ca. 2% DutyCycle) ausgegeben. 
Die Breite des Spikes ändert sich auch nicht wenn ich den Inhalt des 
buffer-Arrays ändere.

Hat jemand Rat woran es liegen könnte bzw. benötigt ihr noch mehr 
Informationen von mir?
Hier noch meine main.c:

/**
  ************************************************************************ 
******
  * File Name          : main.c
  * Description        : Main program body
  ************************************************************************ 
******
  ** This notice applies to any and all portions of this file
  * that are not between comment pairs USER CODE BEGIN and
  * USER CODE END. Other portions of this file, whether
  * inserted by the user or by software development tools
  * are owned by their respective copyright owners.
  *
  * 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 "main.h"
#include "stm32f4xx_hal.h"

/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private variables 
---------------------------------------------------------*/
TIM_HandleTypeDef htim3;
DMA_HandleTypeDef hdma_tim3_ch3;

/* USER CODE BEGIN PV */
/* Private variables 
---------------------------------------------------------*/
uint16_t len, i;
uint32_t buffer[8];
uint32_t myVal;
/* 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_TIM3_Init(void);
void HAL_TIM_MspPostInit(TIM_HandleTypeDef *htim);


/* USER CODE BEGIN PFP */
/* Private function prototypes 
-----------------------------------------------*/

/* USER CODE END PFP */

/* USER CODE BEGIN 0 */

/* 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();

  /* 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_TIM3_Init();

  /* USER CODE BEGIN 2 */
  len = sizeof(buffer);
  buffer[0] = 26;
  buffer[1] = 26;
  buffer[2] = 26;
  buffer[3] = 26;
  buffer[4] = 26;
  buffer[5] = 26;
  buffer[6] = 26;
  buffer[7] = 26;

  //HAL_TIM_Base_Start(&htim3);
  //HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_3);
  HAL_TIM_PWM_Start_DMA(&htim3, TIM_CHANNEL_3, buffer, len);

  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */

  }
  /* USER CODE END 3 */

}

/** System Clock Configuration
*/
void SystemClock_Config(void)
{

  RCC_OscInitTypeDef RCC_OscInitStruct;
  RCC_ClkInitTypeDef RCC_ClkInitStruct;

    /**Configure the main internal regulator output voltage
    */
  __HAL_RCC_PWR_CLK_ENABLE();

  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

    /**Initializes the CPU, AHB and APB busses clocks
    */
  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 = 168;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    _Error_Handler(_FILE_, _LINE_);
  }

    /**Initializes the CPU, AHB and APB busses 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(_FILE_, _LINE_);
  }

    /**Configure the Systick interrupt time
    */
  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

    /**Configure the Systick
    */
  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  /* SysTick_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}

/* TIM3 init function */
static void MX_TIM3_Init(void)
{

  TIM_ClockConfigTypeDef sClockSourceConfig;
  TIM_MasterConfigTypeDef sMasterConfig;
  TIM_OC_InitTypeDef sConfigOC;

  htim3.Instance = TIM3;
  htim3.Init.Prescaler = 1;
  htim3.Init.CounterMode = TIM_COUNTERMODE_DOWN;
  htim3.Init.Period = 52;
  htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
  if (HAL_TIM_Base_Init(&htim3) != HAL_OK)
  {
    _Error_Handler(_FILE_, _LINE_);
  }

  sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
  if (HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig) != HAL_OK)
  {
    _Error_Handler(_FILE_, _LINE_);
  }

  if (HAL_TIM_PWM_Init(&htim3) != HAL_OK)
  {
    _Error_Handler(_FILE_, _LINE_);
  }

  sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
  sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
  if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != 
HAL_OK)
  {
    _Error_Handler(_FILE_, _LINE_);
  }

  sConfigOC.OCMode = TIM_OCMODE_PWM1;
  sConfigOC.Pulse = 26;
  sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
  sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
  if (HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_3) != 
HAL_OK)
  {
    _Error_Handler(_FILE_, _LINE_);
  }

  HAL_TIM_MspPostInit(&htim3);

}

/**
  * Enable DMA controller clock
  */
static void MX_DMA_Init(void)
{
  /* DMA controller clock enable */
  __HAL_RCC_DMA1_CLK_ENABLE();

  /* DMA interrupt init */
  /* DMA1_Stream7_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA1_Stream7_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(DMA1_Stream7_IRQn);

}

/** Configure pins as
        * Analog
        * Input
        * Output
        * EVENT_OUT
        * EXTI
*/
static void MX_GPIO_Init(void)
{

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

}

/* 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(char * file, int line)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return 
state */
  while(1)
  {
  }
  /* 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

/**
  * @}
  */

/**
  * @}
*/

/************************ (C) COPYRIGHT STMicroelectronics *****END OF 
FILE****/

von Andreas S. (igel1)


Lesenswert?

Habe leider keine Zeit, Deinen Code genauer durchzukämmen (und ich kenne 
mich leider auch nicht mit HAL aus), daher hier nur ein Verweis auf 2 
Stellen, die mir verdächtig vorkommen:

Code-Stelle 1:
1
uint32_t buffer[8];
2
3
     // VERDACHT: CCR von TIM3 ist nicht 32bit sondern 16bit
4
     //           breit. Daher nehme ich an, dass Dein buffer-Array
5
     //           auch nur 16bit-Werte enthalten sollte.
6
7
     //           So ganz sicher bin ich mir aber nicht - denn immerhin
8
     //           verlangt die Funktion HAL_TIM_PWM_Start_DMA() laut
9
     //           ihrer Signatur einen Pointer auf 32-bit Werte.
10
11
     //           Da müßte man sich die Innereien der HAL-Funktion
12
     //           einmal näher angucken: machen die alles richtig?
13
     //           Und welchen Teil Deines Array-Wertes schreiben die
14
     //           in Dein CCR-Register (die unteren oder die oberen
15
     //           16 Bit?)


Code-Stelle 2:
1
 /* USER CODE BEGIN 2 */
2
  len = sizeof(buffer);  
3
4
     // VERDACHT: Du erwartest len=8 ?
5
     // aber Du bekommst vermutlich len=32 ...
6
     // korrekt wäre:  len = sizeof(buffer)/sizeof(buffer[0]);
7
8
  buffer[0] = 26;
9
  buffer[1] = 26;
10
  buffer[2] = 26;
11
  buffer[3] = 26;
12
  buffer[4] = 26;
13
  buffer[5] = 26;
14
  buffer[6] = 26;
15
  buffer[7] = 26;
16
17
  //HAL_TIM_Base_Start(&htim3);
18
  //HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_3);
19
  HAL_TIM_PWM_Start_DMA(&htim3, TIM_CHANNEL_3, buffer, len);

Wenn Du die Aufgabenstellung ohne HAL lösen möchtest, so findest Du in 
ST's "AN 4776" (=Application Note zum Thema General purpose timer 
cookbook) im Kapitel 5.3 "Application example: arbitrary waveform 
generation using timer DMA-burst feature" eine sehr detaillierte 
Beschreibung samt Code:
http://www.st.com/content/ccc/resource/technical/document/application_note/group0/91/01/84/3f/7c/67/41/3f/DM00236305/files/DM00236305.pdf/jcr:content/translations/en.DM00236305.pdf

Die Lektüre lohnt in jedem Fall - auch wenn Du es später anders (z.B. 
mit HAL) umsetzen möchtest.

Viele Grüsse

Igel1

: Bearbeitet durch User
von Andreas S. (igel1)


Lesenswert?

@tm200014:  wollte einmal höflichst nachfragen, was aus Deiner 
PWM-Generierung geworden ist und ob Du mit meinen Tipps etwas anfangen 
konntest?

Viele Grüße

Igel1

von bilal ali (Gast)


Lesenswert?

-->wrong
1- uint32_t buffer[8];
2- HAL_TIM_PWM_Start_DMA(&htim3, TIM_CHANNEL_3, buffer, len);



-->correct
1- uint16_t buffer[8];
2- HAL_TIM_PWM_Start_DMA(&htim3,TIM_CHANNEL_3,(uint32_t)&buffer,8);

von Andreas S. (igel1)


Lesenswert?

Cool, was man so alles in 2 Jahren rausfinden kann ;-)

von Cödsöadasä (Gast)


Lesenswert?

Was für ne HAL schoose... hier meine paar Zeilen bare Metal, womit ich 
DMA Duty Cycle auf eine PWM setze:
1
RCC->APB2ENR |= RCC_APB2ENR_TIM16EN;
2
TIM16->DIER = TIM_DIER_UDE; //DMA bei Capture enable
3
TIM16->CCMR1 = (0b110UL << 4) | TIM_CCMR1_OC1PE; //PWM
4
TIM16->CCER = TIM_CCER_CC1E | TIM_CCER_CC1P; //Capture Compare enable
5
TIM16->ARR = (CLK_TIMER / 1000) - 1; //1kHz
6
TIM16->CCR1 = 0;  //PWM am Anfang aus
7
TIM16->BDTR = TIM_BDTR_MOE;
8
TIM16->CR1 = TIM_CR1_CEN;
9
DMA1_Channel1->CPAR = (uint32_t) &TIM16->CCR1;
10
DMA1_Channel1->CMAR = (uint32_t) &arr[0];
11
DMA1_Channel1->CNDTR = 1000;
12
DMA1_Channel1->CCR = DMA_CCR_MINC |DMA_CCR_CIRC | (0b00 << 10)| (0b01 << 8) | DMA_CCR_DIR;
13
DMA1->IFCR = DMA_IFCR_CTCIF1;
14
DMAMUX1_Channel0->CCR = 34; //siehe Datenblatt: Tim6 Update Event
15
DMA1_Channel1->CCR |= DMA_CCR_EN;

Bitte melde dich an um einen Beitrag zu schreiben. Anmeldung ist kostenlos und dauert nur eine Minute.
Bestehender Account
Schon ein Account bei Google/GoogleMail? Keine Anmeldung erforderlich!
Mit Google-Account einloggen
Noch kein Account? Hier anmelden.