Skip to content

Instantly share code, notes, and snippets.

@samdbmg
Created January 26, 2015 13:58
Show Gist options
  • Save samdbmg/11ae653299e0018c0d22 to your computer and use it in GitHub Desktop.
Save samdbmg/11ae653299e0018c0d22 to your computer and use it in GitHub Desktop.
Enable PWM timer output on STM32F4 using peripheral library (not STM Cube)
/* Board support headers */
#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_tim.h"
#include "stm32f4xx_rcc.h"
#define TIMER_BASE_FREQUENCY 72000000
#define PWM_FREQUENCY 40000
#define PWM_TICKS TIMER_BASE_FREQUENCY/PWM_FREQUENCY
#define PWM_COMPARE_VALUE PWM_TICKS/2
/**
* Configure the PWM timer to generate 40kHz
*/
void pwm_timer_setup(void)
{
// Start up timer and GPIO clocks
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
// Configure output pin
GPIO_InitTypeDef GPIO_initstruct;
GPIO_initstruct.GPIO_Pin = GPIO_Pin_6;
GPIO_initstruct.GPIO_Mode = GPIO_Mode_AF;
GPIO_initstruct.GPIO_OType = GPIO_OType_PP;
GPIO_initstruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_initstruct.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_Init(GPIOC, &GPIO_initstruct);
GPIO_PinAFConfig(GPIOC, GPIO_PinSource6, GPIO_AF_TIM3);
// Timer base configuration (TIM3, 16 bit GP timer)
TIM_TimeBaseInitTypeDef TIM_initstruct;
TIM_initstruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_initstruct.TIM_Prescaler = 0;
TIM_initstruct.TIM_Period = PWM_TICKS;
TIM_initstruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_initstruct);
// PWM Channel 1 configuration
TIM_OCInitTypeDef TIM_ocstruct;
TIM_ocstruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_ocstruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_ocstruct.TIM_Pulse = PWM_COMPARE_VALUE;
TIM_ocstruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_ocstruct);
// Activate TIM3 preloads
TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM3, ENABLE);
TIM_Cmd(TIM3, ENABLE);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment