PWC — 睡眠 + TMR2 唤醒
固件库: AT32F403A_407_Firmware_Library V2.2.2
芯片: AT32
源文件: AT32/AT32F403A_407_Firmware_Library_V2.2.2/project/at_start_f403a/examples/pwc/sleep_tmr2/src/main.c
功能简介
本示例演示睡眠(Sleep)低功耗模式。CPU 停止运行,但外设继续工作。任何中断都能唤醒 CPU,唤醒后立即恢复执行。
完整代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
#include "at32f403a_407_board.h"
#include "at32f403a_407_clock.h"
void tmr2_config(void)
{
crm_clocks_freq_type crm_clocks_freq_struct = {0};
/* enable tmr 2 clock */
crm_periph_clock_enable(CRM_TMR2_PERIPH_CLOCK, TRUE);
/* get system clock */
crm_clocks_freq_get(&crm_clocks_freq_struct);
/* (systemclock/(systemclock/10000))/10000 = 1Hz(1s) */
tmr_base_init(TMR2, 9999, (crm_clocks_freq_struct.sclk_freq/10000 - 1));
/* config the counting direction */
tmr_cnt_dir_set(TMR2, TMR_COUNT_UP);
/* config the clock divider value */
tmr_clock_source_div_set(TMR2, TMR_CLOCK_DIV1);
/* enable tmr 2 interrupt */
tmr_interrupt_enable(TMR2, TMR_OVF_INT, TRUE);
/* config tmr 2 nvic */
nvic_irq_enable(TMR2_GLOBAL_IRQn, 0, 0);
/* enable tmr 2 */
tmr_counter_enable(TMR2, TRUE);
}
int main(void)
{
__IO uint32_t index = 0;
__IO uint32_t systick_index = 0;
/* congfig the system clock */
system_clock_config();
/* init at start board */
at32_board_init();
/* config priority group */
nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
/* turn on the led light */
at32_led_on(LED2);
at32_led_on(LED3);
at32_led_on(LED4);
/* enable pwc clock */
crm_periph_clock_enable(CRM_PWC_PERIPH_CLOCK, TRUE);
/* config tmr 2 */
tmr2_config();
while(1)
{
at32_led_off(LED2);
/* save systick register configuration */
systick_index = SysTick->CTRL;
systick_index &= ~((uint32_t)0xFFFFFFFE);
/* disable systick */
SysTick->CTRL &= (uint32_t)0xFFFFFFFE;
/* enter sleep mode */
pwc_sleep_mode_enter(PWC_SLEEP_ENTER_WFI);
/* restore systick register configuration */
SysTick->CTRL |= systick_index;
/* wake up from sleep mode */
at32_led_on(LED2);
delay_ms(500);
}
}
|
代码讲解
系统时钟初始化:配置 MCU 的主频和时钟树。不同芯片的时钟配置不同,一般由工具生成。
板级初始化:初始化开发板上的 LED、按键等基础外设。
定时器配置:设置预分频器(PSC)和重装载值(ARR),定时时间 = (PSC+1) × (ARR+1) / 时钟频率。
中断优先级配置:NVIC 设置中断的抢占优先级和子优先级。数字越小优先级越高。
延时:使用系统延时函数控制 LED 翻转间隔。