本帖最后由 suncat0504 于 2024-12-27 12:23 编辑
PWM的应用很广。MB-025自身提供的例程中,使用定时器3在PB4上输出PWM波。
主程序很简单:
s32 main(void) {
u8 dir = 1;
u16 led0pwmval = 0;
DELAY_Init();
CONSOLE_Init(115200);
LED_Init();
// 使用定时器3处理PWM输出
TIM3_PWM_Init(99, 0); //register fractional frequency
while(1) {
DELAY_Ms(4);
if(dir)led0pwmval++;
else led0pwmval--;
if(led0pwmval > 300)dir = 0;
if(led0pwmval == 0)dir = 1;
TIM3->CCR1 = led0pwmval;
}
}
定时器的初始化处理:
void TIM3_PWM_Init(u16 arr, u16 psc) {
RCC->APB1ENR |= RCC_APB1ENR_TIM3EN; //TIM3clock enable
RCC->AHBENR |= RCC_AHBENR_GPIOB; //RCC->APB2ENR|=1<<3; //enablePORTBclock
//SYSCFG->CFGR|=0x1<<11;
GPIOB->AFRL &= (~(GPIO_AFRL_AFR4));
GPIOB->AFRL |= GPIO_AF_MODE1 << (16);
GPIOB->CRL &= (GPIO_CNF_MODE_AF_PP << GPIO_CRL_CNF_MODE_4_Pos); //PB4clear set
GPIOB->CRL |= GPIO_CRL_MODE4 | GPIO_CRL_CNF4_1; // function output
TIM3->ARR = arr;
TIM3->PSC = psc;
TIM3->CCMR1 |= TIM_CCMR1_IC1F_0 | TIM_CCMR1_IC1F_1 | TIM_CCMR1_IC1F_2; //CH1 PWM2 mode
TIM3->CCMR1 |= TIM_CCMR1_OC1PE; //CH1 preloaded enable
TIM3->CCER |= TIM_CCER_CC1E; //OC1 output enable
TIM3->CR1 = TIM_CR1_ARPE; //ARPEenable
TIM3->CR1 |= TIM_CR1_CEN; //enabletiming device1
}
在CN9,标号为56的排针脚上可以测量到PWM波(使用逻辑分析仪):
占空比是递增递减模式变化的,使蓝色LED呈现为渐亮渐灭的变化。
|