1.硬件
2.软件
pwm驱动文件添加 定时器HAL驱动层文件添加 GPIO常用函数 定时器输出PWM配置步骤 main.c程序
# include "sys.h"
# include "delay.h"
# include "led.h"
# include "pwm.h" int main ( void )
{ HAL_Init ( ) ; stm32_clock_init ( RCC_PLL_MUL9) ; led_init ( ) ; pwm_init ( 500 - 1 , 72 - 1 ) ; uint16_t i = 0 ; while ( 1 ) { for ( i = 0 ; i < 300 ; i++ ) { pwm_compare_set ( i) ; delay_ms ( 10 ) ; } for ( i = 0 ; i < 300 ; i++ ) { pwm_compare_set ( 300 - i) ; delay_ms ( 10 ) ; }
}
}
**timer_init(500 - 1, 720 - 1);//定时500ms
**语句定时参考
# include "led.h"
# include "sys.h"
void led_init ( void )
{ GPIO_InitTypeDef gpio_initstruct; __HAL_RCC_GPIOB_CLK_ENABLE ( ) ; gpio_initstruct. Pin = GPIO_PIN_8 | GPIO_PIN_9; gpio_initstruct. Mode = GPIO_MODE_OUTPUT_PP; gpio_initstruct. Pull = GPIO_PULLUP; gpio_initstruct. Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init ( GPIOB, & gpio_initstruct) ; led1_off ( ) ; led2_off ( ) ;
}
void led1_on ( void )
{ HAL_GPIO_WritePin ( GPIOB, GPIO_PIN_8, GPIO_PIN_RESET) ;
}
void led1_off ( void )
{ HAL_GPIO_WritePin ( GPIOB, GPIO_PIN_8, GPIO_PIN_SET) ;
}
void led1_toggle ( void )
{ HAL_GPIO_TogglePin ( GPIOB, GPIO_PIN_8) ;
}
void led2_on ( void )
{ HAL_GPIO_WritePin ( GPIOB, GPIO_PIN_9, GPIO_PIN_RESET) ;
}
void led2_off ( void )
{ HAL_GPIO_WritePin ( GPIOB, GPIO_PIN_9, GPIO_PIN_SET) ;
}
void led2_toggle ( void )
{ HAL_GPIO_TogglePin ( GPIOB, GPIO_PIN_9) ;
}
# ifndef __LED_H__
# define __LED_H__ void led_init ( void ) ;
void led1_on ( void ) ;
void led1_off ( void ) ;
void led1_toggle ( void ) ;
void led2_on ( void ) ;
void led2_off ( void ) ;
void led2_toggle ( void ) ; # endif
# include "pwm.h" TIM_HandleTypeDef pwm_handle = { 0 } ;
void pwm_init ( uint16_t arr, uint16_t psc)
{ TIM_OC_InitTypeDef pwm_config = { 0 } ; pwm_handle. Instance = TIM4; pwm_handle. Init. Prescaler = psc; pwm_handle. Init. Period = arr; pwm_handle. Init. CounterMode = TIM_COUNTERMODE_UP; HAL_TIM_PWM_Init ( & pwm_handle) ; pwm_config. OCMode = TIM_OCMODE_PWM1; pwm_config. Pulse = arr/ 2 ; pwm_config. OCPolarity = TIM_OCPOLARITY_LOW; HAL_TIM_PWM_ConfigChannel ( & pwm_handle, & pwm_config, TIM_CHANNEL_3) ; HAL_TIM_PWM_Start ( & pwm_handle, TIM_CHANNEL_3) ;
}
void HAL_TIM_PWM_MspInit ( TIM_HandleTypeDef * htim)
{ if ( htim-> Instance == TIM4) { GPIO_InitTypeDef gpio_initstruct; __HAL_RCC_GPIOB_CLK_ENABLE ( ) ; __HAL_RCC_TIM4_CLK_ENABLE ( ) ; gpio_initstruct. Pin = GPIO_PIN_8; gpio_initstruct. Mode = GPIO_MODE_AF_PP; gpio_initstruct. Pull = GPIO_PULLUP; gpio_initstruct. Speed = GPIO_SPEED_FREQ_HIGH; HAL_GPIO_Init ( GPIOB, & gpio_initstruct) ; }
}
void pwm_compare_set ( uint16_t val)
{ __HAL_TIM_SET_COMPARE ( & pwm_handle, TIM_CHANNEL_3, val) ;
}
# ifndef __PWM_H__
# define __PWM_H__ # include "sys.h" void pwm_init ( uint16_t arr, uint16_t psc) ;
void pwm_compare_set ( uint16_t val) ; # endif
3.实物效果
硬件模块接线 LED1正—>VCC LED1负—>PB8 ST-Link下载方式实验现象 使用定时器4通道3生成PWM波控制LED1实现呼吸灯。 频率:2kHz,PSC=71,ARR=499
LED1连接STM32F103的PB8管脚,通过产品手册可知其在定时器4通道3。