在定时器的输出模式中,有一种输出模式—翻转模式,通过使用该模式,可以使用一个定时器不同通道输出移相PWM波形。关于翻转模式,当核心计数器与比较捕获寄存器的值相同时,翻转该通道的电平。
使用翻转模式配置输出移相PWM波形代码如下:
/********************************** (C) COPYRIGHT ******************************* * File Name : main.c * Author : WCH * Version : V1.0.0 * Date : 2021/06/06 * Description : Main program body. * Copyright (c) 2021 Nanjing Qinheng Microelectronics Co., Ltd. * SPDX-License-Identifier: Apache-2.0 *******************************************************************************/ /* *@Note PWM输出例程: TIM1_CH1(PA8) 本例程演示 TIM_CH1(PA8) 引脚在 PWM模式1和PWM模式2 下,输出 PWM。 */ #include "debug.h" /********************************************************************* * @fn TIM1_OutCompare_Init * * @brief Initializes TIM1 output compare. * * @param arr - the period value. * psc - the prescaler value. * ccp - the pulse value. * * @return none */ void TIM1_PWMOut_Init(void) { GPIO_InitTypeDef GPIO_InitStructure={0}; TIM_OCInitTypeDef TIM_OCInitStructure={0}; TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure={0}; RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA | RCC_APB2Periph_TIM1, ENABLE ); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8|GPIO_Pin_9|GPIO_Pin_10|GPIO_Pin_11; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init( GPIOA, &GPIO_InitStructure ); TIM_TimeBaseInitStructure.TIM_Period = 4000-1; TIM_TimeBaseInitStructure.TIM_Prescaler = 14400-1; TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0; TIM_TimeBaseInit( TIM1, &TIM_TimeBaseInitStructure); TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Toggle; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Set; TIM_OCInitStructure.TIM_Pulse = 0; TIM_OC1Init( TIM1, &TIM_OCInitStructure ); TIM_OCInitStructure.TIM_Pulse = 1000; TIM_OC2Init( TIM1, &TIM_OCInitStructure ); TIM_OCInitStructure.TIM_Pulse = 2000; TIM_OC3Init( TIM1, &TIM_OCInitStructure ); TIM_OCInitStructure.TIM_Pulse = 3000; TIM_OC4Init( TIM1, &TIM_OCInitStructure ); TIM_CtrlPWMOutputs(TIM1, ENABLE ); TIM_OC1PreloadConfig( TIM1, TIM_OCPreload_Disable ); TIM_OC2PreloadConfig( TIM1, TIM_OCPreload_Disable ); TIM_OC3PreloadConfig( TIM1, TIM_OCPreload_Disable ); TIM_OC4PreloadConfig( TIM1, TIM_OCPreload_Disable ); TIM_ARRPreloadConfig( TIM1, ENABLE ); TIM_Cmd( TIM1, ENABLE ); } /********************************************************************* * @fn main * * @brief Main program. * * @return none */ int main(void) { USART_Printf_Init(115200); printf("SystemClk:%d\r\n",SystemCoreClock); TIM1_PWMOut_Init(); while(1); }
程序和正常配置PWM输出代码差不多,只是将PWM模式改为翻转模式,比较寄存器的值要根据移相的需求进行配置,注意大小不要超过设置的重装载值。该种方式配置输出的PWM波形占空比固定为50%。输出波形如下:
标签:TimeBaseInitStructure,TIM1,CH32,移相,TIM,OCInitStructure,GPIO,MCU,PWM From: https://www.cnblogs.com/liaigu/p/17861503.html