#include "stm32f10x.h"
/* 声明GPIO设置函数 */
void GPIO_Config(void);
/* 声明TIM3设置函数 */
void TIM3_Config(void);
/* 声明四个通道溢出数值 */
uint16_t CCR1_Val = 333;
uint16_t CCR2_Val = 249;
uint16_t CCR3_Val = 166;
uint16_t CCR4_Val = 83;
/* 定义一个预分频系数 */
uint16_t PrescalerValue = 0;
int main(void)
{
/* 设置PC6,7,8,9为推挽输出 */
GPIO_Config();
/* 设置TIM3重映射后的四个通道产生四路不同的PWM波形 */
TIM3_Config();
/* TIM3预装载寄存器使能 */
TIM_ARRPreloadConfig(TIM3, ENABLE);
/* TIM3 使能 */
TIM_Cmd(TIM3, ENABLE);
while(1)
{
}
}
void GPIO_Config()
{
/* 定义一个GPIO_InitTypeDef类型的结构体,该类型在stm32f10x_gpio.h中定义 */
GPIO_InitTypeDef GPIO_InitStructure;
/* 使能 GPIOC和AFIO 时钟 */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC | RCC_APB2Periph_AFIO, ENABLE);
/* 配置PC6,7,8,9管脚为重映射的推挽输出,
即重映射的TIM3的channel1, 2, 3 and 4 */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7 | GPIO_Pin_8 | GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void TIM3_Config(void)
{
/* 定义一个TIM_TimeBaseInitTypeDef类型的结构体,该类型在stm32f10x_tim.h中定义 */
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
/* 定义一个TIM_OCInitTypeDef类型的结构体,该类型在stm32f10x_tim.h中定义 */
TIM_OCInitTypeDef TIM_OCInitStructure;
/* 使能 TIM3 时钟 */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
/* TIM3完全重映射,即映射到PC6,7,8,9 */
GPIO_PinRemapConfig(GPIO_FullRemap_TIM3, ENABLE);
/* 计算预分频系数 */
PrescalerValue = (uint16_t) (SystemCoreClock / 24000000) - 1;
/* 时基设置,TIM3为向上计数 */
TIM_TimeBaseStructure.TIM_Period = 665;
TIM_TimeBaseStructure.TIM_Prescaler = PrescalerValue;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
/* TIM3为PWM1模式,输出使能,溢出值为CCR1_Val */
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
/* 调用通道1初始化程序进行初始化,使能通道1预装载寄存器 */
TIM_OC1Init(TIM3, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Enable);
/* 溢出值为CCR2_Val,进行初始化,使能通道2预装载寄存器 */
TIM_OCInitStructure.TIM_Pulse = CCR2_Val;
TIM_OC2Init(TIM3, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM3, TIM_OCPreload_Enable);
/* 溢出值为CCR3_Val,进行初始化,使能通道3预装载寄存器 */
TIM_OCInitStructure.TIM_Pulse = CCR3_Val;
TIM_OC3Init(TIM3, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM3, TIM_OCPreload_Enable);
/* 溢出值为CCR4_Val,进行初始化,使能通道4预装载寄存器 */
TIM_OCInitStructure.TIM_Pulse = CCR4_Val;
TIM_OC4Init(TIM3, &TIM_OCInitStructure);
TIM_OC4PreloadConfig(TIM3, TIM_OCPreload_Enable);
}
|