一、GPIO初始化
GPIO配置如下
GPIOA->CRH&=0XFFFFF000; //清除PA8,9,10配置
GPIOA->CRH|=0X00000BBB; //PA8,9,10推挽复用功能输出 B=1011
GPIOB->CRH&=0X000FFFFF; //清除PB13,14,15配置
GPIOB->CRL|=0XBBB00000; //PB13,14,15推挽复用功能输出
接下来是引脚复用
RCC->APB2ENR|=1<<0; //开启辅助时钟
AFIO->MAPR&=0XFFFFFF3F; //清除MAPR的[7:6]
//TIM1 无重映像,TIM1_CH1,2,3->PA8,9,10;TIM1_CHN1,2,3->PB13,14,15
二、定时器1初始化
TIM1->CCMR1|=6<<4; //CH1 PWM1模式
TIM1->CCMR1|=1<<3; //CH1预装载使能
TIM1->CCMR1|=6<<12; //CH2 PWM1模式
TIM1->CCMR1|=1<<11; //CH2预装载使能
TIM1->CCER|=5; //CH1,CH1N 输出使能,高电平有效
TIM1->CCER|=5<<4; //CH2,CH2N 输出使能,高电平有效
TIM1->ARR=arr; //设定计数器自动重装值
TIM1->PSC=psc; //预分频器分频
TIM1->CCR1=400; //占空比
TIM1->BDTR|=1<<15; // 刹车使能位置1,开启所有输出通道
TIM1->BDTR|=0xCD; // 死区时间设定
TIM1->CR1 |= 1; //开始计时
三 代码
/*定时器1,3路互补PWM输出CH1,CH1N,CH2,CH2N,CH3,CH3N*/
void 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&=0XFFFFF000; //清除PA8,9,10配置
GPIOA->CRH|=0X00000BBB; //PA8,9,10推挽复用功能输出 B=1011
GPIOB->CRH&=0X000FFFFF; //清除PB13,14,15配置
GPIOB->CRH|=0XBBB00000; //PB13,14,15推挽复用功能输出
GPIOA->ODR|=1<<8;
GPIOA->ODR|=1<<9;GPIOA->ODR|=1<<10;
GPIOB->ODR|=1<<13;
GPIOB->ODR|=1<<14;GPIOB->ODR|=1<<15;
TIM1->CCR1=400;
TIM1->CCR2=800;
TIM1->CCR3=1200;
TIM1->ARR=arr; //设定计数器自动重装值
TIM1->PSC=psc; //预分频器不分频
TIM1->BDTR|=0xCD; // 死区时间设定
TIM1->CCER|=1<<0;//TIM1CH1通道开关使能
TIM1->CCER|=1<<2;//TIM1CH1N 通道开关
TIM1->CCER|=1<<4;
TIM1->CCER|=1<<6;
TIM1->CCER|=1<<8;
TIM1->CCER|=1<<10;
TIM1->CCMR1|=7<<4; //CH1 PWM2模式
TIM1->CCMR1|=1<<3; //CH1预装载使能
TIM1->CCMR1|=7<<12; //CH2 PWM2模式
TIM1->CCMR1|=1<<11; //CH1预装载使能
TIM1->CCMR2|=7<<4; //CH3 PWM2模式
TIM1->CCMR2|=1<<11; //CH3预装载使能
TIM1->CR1|=0X80;// CR1 ARPE自动重装载预装载允许位使能
TIM1->BDTR|=1<<15; //刹车使能位置1,开启所有输出通道
TIM1->CR1|=0X01; //使能定时计数器1
}