蓝桥杯嵌入式之PWM普通输出_Again

备注:由于疫情影响,蓝桥杯赛事推迟数月,现在距离初赛还有20天左右,在此准备期间,以博客作笔记,记录代码和注意事项。

PWM普通输出模式:同一定时器下的不同通道输出PWM频率一定相同,占空比可以不同
注意同一定时器下的不同通道频率一定相同,被这种输出模式决定,也是它的缺点。

代码
初始化函数

#include "pwm.h"

void Pwm_Init(u16 fre, u8 duty1,u8 duty2)
{
	u16 arr;

	GPIO_InitTypeDef GPIO_InitStructure;
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
	TIM_OCInitTypeDef  TIM_OCInitStructure;

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);	//PA6->TIM3_CH1    PA7->TIM3_CH2
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

	GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_6 | GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;		  //推挽复用输出
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

	arr = 1000000 / fre;
	TIM_TimeBaseStructure.TIM_Period = arr - 1;//周期
    TIM_TimeBaseStructure.TIM_Prescaler = 71;// 72分频
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;//模式为PWM输出2
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse = (arr - 1) * duty1 / 100;//通道一占空比
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;//极性为低
    TIM_OC1Init(TIM3, &TIM_OCInitStructure);

	TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;//模式为PWM输出2
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructure.TIM_Pulse = (arr - 1) * duty2 / 100;//通道二占空比
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_Low;//极性为低
    TIM_OC2Init(TIM3, &TIM_OCInitStructure);

	TIM_Cmd(TIM3, ENABLE);
}

注意:普通输出模式不需要设置中断处理,配置较为简单。

调用

Pwm_Init(2000, 20, 80);

你可能感兴趣的:(蓝桥杯嵌入式,嵌入式,stm32)