代码和详解:
//TIM1_CH1 PWM输出初始化
//arr:自动重装值
//psc:时钟预分频数
void TIM1_PWM_Init(u16 arr,u16 psc)
{
RCC->APB2ENR|=1<<11; //TIM1时钟使能
RCC->APB2ENR|=1<<2; //使能PORTA时钟
RCC->APB2ENR|=1<<3; //使能PORTB时钟
RCC->APB2ENR|=1<<0; //开启复用时钟
GPIOA->CRH&=0XFFFF0000; //PA8,9,10,11清除之前的设置
GPIOA->CRH|=0X0000BBBB; //PA8,9,10,11复用功能输出
GPIOB->CRH&=0X000FFFFF; //PB13,14,15清除之前的设置
GPIOB->CRH|=0XBBB00000; //PB13,14,15复用功能输出
GPIOB->ODR|=1<<13; //PB13 输出上拉,低电平有效
GPIOB->ODR|=1<<14; //PB14
GPIOB->ODR|=1<<15; //PB15
GPIOA->ODR|=1<<8; //PA8
GPIOA->ODR|=1<<9; //PA9
GPIOA->ODR|=1<<10; //PA10
TIM1->ARR=arr; //设定计数器自动重装值 ①1
TIM1->PSC=psc; //预分频器设置 ②2
TIM1->CCER|=1<<0; //TIM1CH1 输出使能,高电平有效 ③3
TIM1->CCER|=1<<4; //TIM1CH2 输出使能
TIM1->CCER|=1<<8; //TIM1CH3 输出使能
TIM1->CCER|=1<<12; //TIM1CH4 输出使能
TIM1->CCER|=1<<2; //TIM1CH1N 互补输出使能
TIM1->CCER|=1<<6; //TIM1CH2N 互补输出使能
TIM1->CCER|=1<<10; //TIM1CH3N 互补输出使能
TIM1->CCMR1|=7<<4; //CH1 PWM2模式 ④4
TIM1->CCMR1|=1<<3; //CH1预装载使能
TIM1->CCMR1|=7<<12; //CH2 PWM2模式
TIM1->CCMR1|=1<<11; //CH2预装载使能
TIM1->CCMR2|=7<<4; //CH3 PWM2模式
TIM1->CCMR2|=1<<3; //CH3预装载使能
TIM1->CCMR2|=7<<12; //CH4 PWM2模式
TIM1->CCMR2|=1<<11; //CH4预装载使能
TIM1->BDTR|=0x14; //死区时间设置 ⑤5
TIM1->BDTR|=1<<15; //MOE 主输出使能 ⑥6
TIM1->CR1 |= 0x80; //ARPE使能,开始所有输出通道,默认向上计数 ⑦7
TIM1->CR1 |= 0x01; //使能计数器
}
int main(void)
{
Stm32_Clock_Init(9); //系统时钟设置
delay_init(72); //延时初始化
TIM1_PWM_Init(499,7199); // 72M/7200=10khz, 1/10khz * 500=50ms ⑧8
while(1)
{
TIM1->CCR1=250; //占空比:50% 低电平时长25ms ⑨9
TIM1->CCR2=125; //占空比:75% 低电平时长12.5ms
TIM1->CCR3=50; //占空比:90% 低电平时长5ms
TIM1->CCR4=25; //占空比:95% 低电平时长2.5ms
}
}
|