一,功能描述
使用定时器的四个比较捕获通道输出四路PWM信号并观察效果。
二,软硬件平台
硬件
沁恒官方评估版CH32V307-R1-1V0。
软件
MRS生成的空白工程。
三,程序编写
直接操作寄存器失败之后,参考沁恒的demo编写代码如下,期望效果输出4路中心对齐PWM信号,频率为1/2 CK_CNT,为7.2kHZ,占空比依次为20%,40%,60%,80%
void PWM_Init()
{
GPIO_InitTypeDef GPIO_InitStructure={0};
TIM_OCInitTypeDef TIM_OCInitStructure={0};
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure={0};
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOE | RCC_APB2Periph_TIM1 | RCC_APB2Periph_AFIO, ENABLE );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init( GPIOE, &GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
GPIO_Init( GPIOE, &GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_Init( GPIOE, &GPIO_InitStructure );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14;
GPIO_Init( GPIOE, &GPIO_InitStructure ); //配置使用的IO
GPIO_PinRemapConfig(GPIO_FullRemap_TIM1, ENABLE); //重映射IO
TIM_TimeBaseInitStructure.TIM_Period = 10000;
TIM_TimeBaseInitStructure.TIM_Prescaler = 0;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_CenterAligned1;
TIM_TimeBaseInit( TIM1, &TIM_TimeBaseInitStructure); //配置核心计数器工作模式
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 5000;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init( TIM1, &TIM_OCInitStructure );
TIM_OC2Init( TIM1, &TIM_OCInitStructure );
TIM_OC3Init( TIM1, &TIM_OCInitStructure );
TIM_OC4Init( TIM1, &TIM_OCInitStructure ); //配置比较输出通道
TIM_CtrlPWMOutputs(TIM1, ENABLE ); //高级定时器置位MOE
TIM_OC1PreloadConfig( TIM1, TIM_OCPreload_Disable );
TIM_OC2PreloadConfig( TIM1, TIM_OCPreload_Disable );
TIM_OC3PreloadConfig( TIM1, TIM_OCPreload_Disable );
TIM_OC4PreloadConfig( TIM1, TIM_OCPreload_Disable ); //禁止ccr预装载
TIM_ARRPreloadConfig( TIM1, ENABLE ); //开启核心计数器自动重装载
TIM_Cmd( TIM1, ENABLE ); //开启核心计数器
}
int main(void)
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
SystemCoreClockUpdate();
Delay_Init();
USART_Printf_Init(115200);
printf("SystemClk:%d\r\n",SystemCoreClock);
printf( "ChipID:%08x\r\n", DBGMCU_GetCHIPID() );
printf("This is printf example\r\n");
PWM_Init();
TIM1->CH1CVR = 2000;
TIM1->CH2CVR = 4000;
TIM1->CH3CVR = 6000;
TIM1->CH4CVR = 8000;
while(1)
{
}
}
四,观察现象
使用逻辑分析仪观察到的信号如下
![](https://i-blog.csdnimg.cn/blog_migrate/fee751609c38f6ae9b7d3928b13d7eb8.png)