Timer Interrupt
该示例使用 TIM ,实现定时1s的定时功能。
为了便于观察现象,短接P0_0和LED0。
定时时间到,触发中断,在中断处理函数中翻转P0_0,改变GPIO输出极性,实现LED0每秒闪烁。
环境需求
该示例支持以下开发套件:
Hardware Platforms |
Board Name |
---|---|
RTL87x2G HDK |
RTL87x2G EVB |
更多信息请参考快速入门。
硬件连线
连接P0_0和LED0小灯。
LED驱动电路如下图所示。

LED驱动电路图
编译和下载
该示例的工程路径如下:
Project file: samples\peripheral\timer\timer_interrupt\proj\rtl87x2g\mdk
Project file: samples\peripheral\timer\timer_interrupt\proj\rtl87x2g\gcc
请按照以下步骤操作构建并运行该示例:
打开工程文件。
按照 快速入门 中 编译APP Image 给出的步骤构建目标文件。
编译成功后,在路径
mdk\bin
或gcc\bin
下会生成 app binapp_MP_xxx.bin
文件。按下复位按键,开始运行。
测试验证
当EVB启动后,在Debug Analyzer工具内观察如下log。
Start timer interrupt test!
当P0_0和LED0连接后,LED0每1秒闪烁一次。
代码介绍
该章节分为以下几个部分:
源码路径
工程路径:
sdk\samples\peripheral\timer\timer_interrupt\proj
源码路径:
sdk\samples\peripheral\timer\timer_interrupt\src
该工程的工程文件代码架构如下:
└── Project: input_polling
└── secure_only_app
└── Device includes startup code
├── startup_rtl.c
└── system_rtl.c
├── CMSIS includes CMSIS header files
├── CMSE Library Non-secure callable lib
├── Lib includes all binary symbol files that user application is built on
└── rtl87x2g_io.lib
├── Peripheral includes all peripheral drivers and module code used by the application
├── rtl_rcc.c
├── rtl_pinmux.c
├── rtl_nvic.c
└── rtl_tim.c
└── APP includes the ble_peripheral user application implementation
└── main_ns.c
└── io_timer.c
初始化
初始化流程包括了 board_gpio_init
, driver_gpio_init
和 driver_timer_init
。
board_gpio_init
中包含了PAD与PINMUX设置。
配置PAD:设置引脚、PINMUX模式、PowerOn、内部上拉。
配置PINMUX:分配引脚为GPIO功能。
driver_gpio_init
包含了对GPIO外设的初始化。
使能PCC时钟。
设置GPIO的输出引脚
GPIO_Pin
为P0_0。在GPIO初始化中,设置
GPIO_Dir
为输出模式。
RCC_PeriphClockCmd(APBPeriph_GPIOA, APBPeriph_GPIOA_CLOCK, ENABLE);
...
GPIO_InitStruct.GPIO_Pin = GPIO_PIN;
GPIO_InitStruct.GPIO_Dir = GPIO_DIR_OUT;
driver_timer_init
包含了对TIM外设的初始化。
使能PCC时钟。
设置
TIM_PWM_En
为DISABLE,即TIMER模式。设置
TIM_Period
为TIMER_PERIOD(40000000-1),即定时1s。设置
TIM_Mode
为TIM_Mode_UserDefine,即用户定义模式。清除TIM2中断;使能TIM2中断;使能TIM2。
RCC_PeriphClockCmd(APBPeriph_TIMER, APBPeriph_TIMER_CLOCK, ENABLE);
...
TIM_InitStruct.TIM_PWM_En = DISABLE;
TIM_InitStruct.TIM_Period = TIMER_PERIOD ;
TIM_InitStruct.TIM_Mode = TIM_Mode_UserDefine;
TIM_TimeBaseInit(TIMER_NUM, &TIM_InitStruct);
...
TIM_ClearINT(TIMER_NUM);
TIM_INTConfig(TIMER_NUM, ENABLE);
TIM_Cmd(TIMER_NUM, ENABLE);
功能实现
TIM2定时时间到,触发中断,进入中断处理函数 Timer2_Handler
。
清除TIM2中断,失能TIM2。
判断当前LED状态,翻转GPIO_PIN电平。
重新使能TIM2。
void TIMER_Handler(void)
{
TIM_ClearINT(TIMER_NUM);
TIM_Cmd(TIMER_NUM, DISABLE);
if (!LED_Status)
{
GPIO_WriteBit(GPIO_PORT, GPIO_PIN, (BitAction)(1));
LED_Status = 1;
}
else
{
GPIO_WriteBit(GPIO_PORT, GPIO_PIN, (BitAction)(0));
LED_Status = 0;
}
//Add user code here
TIM_Cmd(TIMER_NUM, ENABLE);
}