1.硬件
2.软件
timer驱动文件添加 定时器HAL驱动层文件添加 GPIO常用函数 定时器中断配置流程 main.c程序
# include "sys.h"
# include "delay.h"
# include "led.h"
# include "timer.h"
int main ( void )
{
HAL_Init ( ) ;
stm32_clock_init ( RCC_PLL_MUL9) ;
led_init ( ) ;
timer_init ( 5000 - 1 , 7200 - 1 ) ;
while ( 1 )
{
}
}
**timer_init(5000 - 1, 7200 - 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 "timer.h"
# include "led.h"
TIM_HandleTypeDef timer_handle = { 0 } ;
void timer_init ( uint16_t arr, uint16_t psc)
{
timer_handle. Instance = TIM2;
timer_handle. Init. Prescaler = psc;
timer_handle. Init. Period = arr;
timer_handle. Init. CounterMode = TIM_COUNTERMODE_UP;
timer_handle. Init. AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE;
HAL_TIM_Base_Init ( & timer_handle) ;
HAL_TIM_Base_Start_IT ( & timer_handle) ;
}
void HAL_TIM_Base_MspInit ( TIM_HandleTypeDef * htim)
{
if ( htim-> Instance == TIM2)
{
__HAL_RCC_TIM2_CLK_ENABLE ( ) ;
HAL_NVIC_SetPriority ( TIM2_IRQn, 2 , 2 ) ; 设置优先级
HAL_NVIC_EnableIRQ ( TIM2_IRQn) ;
}
}
void TIM2_IRQHandler ( void )
{
HAL_TIM_IRQHandler ( & timer_handle) ;
}
void HAL_TIM_PeriodElapsedCallback ( TIM_HandleTypeDef * htim)
{
if ( htim-> Instance == TIM2)
{
led1_toggle ( ) ;
}
}
# ifndef __TIMER_H__
# define __TIMER_H__
# include "sys.h"
void timer_init ( uint16_t arr, uint16_t psc) ;
# endif
3.实物效果
硬件模块接线 LED1正—>VCC LED1负—>PB8 ST-Link下载方式实验现象 LED1以500ms亮灭状态翻转。