1. 程式人生 > >STM32輸出PWM

STM32輸出PWM

-s font scale bsp 上拉 pwm puts config _cmd

最近要用STM32來輸出PWM,花了一個晚上寫完了,記錄一下

(我用的是STM32F303CCT6)

1.打開定時器時鐘

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

2.打開輸出引腳的GPIO時鐘

RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

3.配置相應引腳為 AF模式(具體AFx要看手冊)

GPIO_PinAFConfig(GPIOA, GPIO_PinSource6, GPIO_AF_2);

4.初始化輸出引腳為 AF模式, 推挽輸出, 上拉, 速度為GPIO_Speed_Level_3

GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF; //PA6
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_Level_3;
GPIO_Init(GPIOA, &GPIO_InitStruct);

5.定時器設置( 頻率 = 72000000÷(arr+1)÷(psc+1))

TIM_TimeBaseStruct.TIM_Period = 999; //arr


TIM_TimeBaseStruct.TIM_Prescaler = 1439;//psc
TIM_TimeBaseStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStruct.TIM_RepetitionCounter = 0;//重復溢出多少次進中斷
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStruct);

6.定時器通道設置 PWM模式1, 輸出極性高, 允許輸出

TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;


TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStruct);

7.打開定時器

TIM_Cmd(TIM3, ENABLE);

8.設置占空比 Duty = pwmval ÷ arr

TIM_SetCompare1(TIM3, 99);// pwmval Duty = arr/pwmval

9.全部代碼如下

GPIO_InitTypeDef GPIO_InitStruct;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStruct;
TIM_OCInitTypeDef TIM_OCInitStruct;

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

GPIO_PinAFConfig(GPIOA, GPIO_PinSource6, GPIO_AF_2);

GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_6;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_Level_3;
GPIO_Init(GPIOA, &GPIO_InitStruct);

TIM_TimeBaseStruct.TIM_Period = 999; //arr
TIM_TimeBaseStruct.TIM_Prescaler = 1439;// psc
TIM_TimeBaseStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStruct.TIM_RepetitionCounter = 0;//重復溢出多少次進中斷
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStruct);

TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStruct);
TIM_OC2Init(TIM3, &TIM_OCInitStruct);

TIM_Cmd(TIM3, ENABLE);

TIM_SetCompare1(TIM3, 99);//pwmval

在STM32中,PWM輸出的 頻率,占空比,模式 有好幾個不同的參數設置

STM32輸出PWM