资深版主
- 积分
- 10541
- 金钱
- 10541
- 注册时间
- 2017-2-18
- 在线时间
- 1908 小时
|
http://www.openedv.com/forum.php ... &extra=page%3D1
论坛有用户不止怎么利用定时器输出4路PWM,所写改了这个程序支持4路PWM输出程序基于阿波罗F767的PWM输出实验例程修改(HAL库版本)
整个工程最重要的是TIM3_PWM_Init()和HAL_TIM_PWM_MspInit()
[mw_shl_code=c,true]//TIM3 PWM部分初始化
//PWM输出初始化
//arr:自动重装值
//psc:时钟预分频数
void TIM3_PWM_Init(u16 arr,u16 psc)
{
TIM3_Handler.Instance=TIM3; //定时器3
TIM3_Handler.Init.Prescaler=psc; //定时器分频
TIM3_Handler.Init.CounterMode=TIM_COUNTERMODE_UP;//向上计数模式
TIM3_Handler.Init.Period=arr; //自动重装载值
TIM3_Handler.Init.ClockDivision=TIM_CLOCKDIVISION_DIV1;
HAL_TIM_PWM_Init(&TIM3_Handler); //初始化PWM
TIM3_CHxHandler.OCMode=TIM_OCMODE_PWM1; //模式选择PWM1
TIM3_CHxHandler.Pulse=arr/2; //设置比较值,此值用来确定占空比,
//默认比较值为自动重装载值的一半,即占空比为50%
TIM3_CHxHandler.OCPolarity=TIM_OCPOLARITY_LOW; //输出比较极性为低
HAL_TIM_PWM_ConfigChannel(&TIM3_Handler,&TIM3_CHxHandler,TIM_CHANNEL_1);//配置TIM3通道1
HAL_TIM_PWM_ConfigChannel(&TIM3_Handler,&TIM3_CHxHandler,TIM_CHANNEL_2);//配置TIM3通道2
HAL_TIM_PWM_ConfigChannel(&TIM3_Handler,&TIM3_CHxHandler,TIM_CHANNEL_3);//配置TIM3通道3
HAL_TIM_PWM_ConfigChannel(&TIM3_Handler,&TIM3_CHxHandler,TIM_CHANNEL_4);//配置TIM3通道4
HAL_TIM_PWM_Start(&TIM3_Handler,TIM_CHANNEL_1);//开启PWM通道1
HAL_TIM_PWM_Start(&TIM3_Handler,TIM_CHANNEL_2);//开启PWM通道2
HAL_TIM_PWM_Start(&TIM3_Handler,TIM_CHANNEL_3);//开启PWM通道3
HAL_TIM_PWM_Start(&TIM3_Handler,TIM_CHANNEL_4);//开启PWM通道4
}
//定时器底层驱动,时钟使能,引脚配置
//此函数会被HAL_TIM_PWM_Init()调用
//htim:定时器句柄
void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim)
{
GPIO_InitTypeDef GPIO_Initure;
__HAL_RCC_TIM3_CLK_ENABLE(); //使能定时器3
__HAL_RCC_GPIOA_CLK_ENABLE(); //开启GPIOA时钟
__HAL_RCC_GPIOB_CLK_ENABLE(); //开启GPIOB时钟
GPIO_Initure.Pin=GPIO_PIN_0|GPIO_PIN_1; //PB0,PB1复用为TIM3_CH3,TIM3_CH4
GPIO_Initure.Mode=GPIO_MODE_AF_PP; //复用推完输出
GPIO_Initure.Pull=GPIO_PULLUP; //上拉
GPIO_Initure.Speed=GPIO_SPEED_HIGH; //高速
GPIO_Initure.Alternate=GPIO_AF2_TIM3; //复用为TIM3
HAL_GPIO_Init(GPIOB,&GPIO_Initure); //初始化GPIOB
GPIO_Initure.Pin=GPIO_PIN_6|GPIO_PIN_7; //PA6,PA7复用为TIM3_CH1,TIM3_CH2
HAL_GPIO_Init(GPIOA,&GPIO_Initure); //初始化GPIOA
}[/mw_shl_code]
main函数如下
[mw_shl_code=c,true]int main(void)
{
Cache_Enable(); //打开L1-Cache
HAL_Init(); //初始化HAL库
Stm32_Clock_Init(432,25,2,9); //设置时钟,216Mhz
delay_init(216); //延时初始化
uart_init(115200); //串口初始化
TIM3_PWM_Init(500-1,108-1); //108M/108=1M的计数频率,自动重装载为500,那么PWM频率为1M/500=2kHZ
while(1)
{
TIM_SetTIM3Compare1(250);
TIM_SetTIM3Compare2(250);
TIM_SetTIM3Compare3(250);
TIM_SetTIM3Compare4(250);
}
}[/mw_shl_code]
|
|