先上代码
void Hw_Timer0_Init(void)
{
//20:100ms 200:10ms 2000:1ms 20000:100us 200000:10us
TIMER_Open(TIMER0, TIMER_PERIODIC_MODE, 200000);
/* Update prescale to set proper resolution. */
TIMER_SET_PRESCALE_VALUE(TIMER0, 1);
/* Enable Timer0 interrupt */
TIMER_EnableInt(TIMER0);
NVIC_EnableIRQ(TMR0_IRQn);
TIMER_Start(TIMER0);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
可以参考注释修改TIMER_Open的参数,想设置为2 000 000 定时1us没有成功,进hardfalt了,没有去细细研究,后续可能会补上。有需要的可以调用官方参考代码中的TIMER_Delay。
整个工程参考代码,这里修改了串口0的IO口为P14 P15
#include <stdio.h>
#include "NuMicro.h"
#include "hw_uart01.h"
#include "hw_timer0.h"
void SYS_Init(void)
{
/* Unlock protected registers */
SYS_UnlockReg();
/* Enable HIRC clock (Internal RC 48MHz) */
CLK_EnableXtalRC(CLK_PWRCTL_HIRCEN_Msk);
/* Wait for HIRC clock ready */
CLK_WaitClockReady(CLK_STATUS_HIRCSTB_Msk);
/* Select HCLK clock source as HIRC and HCLK source divider as 1 */
CLK_SetHCLK(CLK_CLKSEL0_HCLKSEL_HIRC, CLK_CLKDIV0_HCLK(1));
/* Enable UART0 clock */
CLK_EnableModuleClock(UART0_MODULE);
/* Switch UART0 clock source to HIRC */
CLK_SetModuleClock(UART0_MODULE, CLK_CLKSEL1_UART0SEL_HIRC, CLK_CLKDIV0_UART0(1));
/* Enable IP clock */
CLK_EnableModuleClock(TMR0_MODULE);
/* Select IP clock source */
CLK_SetModuleClock(TMR0_MODULE, CLK_CLKSEL1_TMR0SEL_HIRC, 0);
/* Update System Core Clock */
SystemCoreClockUpdate();
/* UART0 RXD=PA.14 and TXD=PA.15 */
SYS->GPA_MFPH = (SYS->GPA_MFPH & ~(SYS_GPA_MFPH_PA14MFP_Msk | SYS_GPA_MFPH_PA15MFP_Msk))|
(SYS_GPA_MFPH_PA14MFP_UART0_TXD | SYS_GPA_MFPH_PA15MFP_UART0_RXD );
/* Enable USCI UART interrupt */
UUART_ENABLE_TRANS_INT(UUART0, UUART_INTEN_RXENDIEN_Msk);
NVIC_EnableIRQ(USCI_IRQn);
/* Lock protected registers */
SYS_LockReg();
}
int main()
{
SYS_Init();
/* Init UART0 to 115200-8n1 for print message */
Hw_Uart0_Init();
Hw_Timer0_Init();
while(1)
{
printf("Hello World\r\n");
App_Func_Delay(100000);//1s
}
}
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
#include "hw_timer0.h"
#include "NuMicro.h"
#include "stdio.h"
//这里一定要加volatile
//大家可以试试不加会有什么BUG,我这里是100%复现
volatile unsigned int g_delay_time = 0;
volatile unsigned int g_delay_flag = 0;
void Hw_Timer0_Init(void)
{
//20:100ms 200:10ms 2000:1ms 20000:100us 200000:10us
TIMER_Open(TIMER0, TIMER_PERIODIC_MODE, 200000);
/* Update prescale to set proper resolution. */
TIMER_SET_PRESCALE_VALUE(TIMER0, 1);
/* Enable Timer0 interrupt */
TIMER_EnableInt(TIMER0);
NVIC_EnableIRQ(TMR0_IRQn);
TIMER_Start(TIMER0);
}
void App_Func_Delay(unsigned int ms)
{
g_delay_time = ms;
while(0 == g_delay_flag);
g_delay_flag = 0;
}
void TMR0_IRQHandler(void)
{
if(g_delay_time)
{
g_delay_time--;
if(0 == g_delay_time)
{
g_delay_flag = 1;
}
}
/* Clear interrupt flag */
TIMER_ClearIntFlag(TIMER0);
}
|