xref: /nrf52832-nimble/rt-thread/components/drivers/hwtimer/README_CN.md (revision 167494296f0543431a51b6b1b83e957045294e05)
1# 定时器设备
2
3## 功能
4
5* 时间测量
6* 周期或单次执行回调函数
7
8## 编译
9
101. 在rtconfig.h添加 `#define RT_USING_HWTIMER`
11
12## 使用流程
13
141. 以读写方式打开设备
152. 设置超时回调函数(如果需要)
163. 根据需要设置定时模式(单次/周期)
174. 设置计数频率(可选)
185. 写入超时值,定时器随即启动
196. 停止定时器(可选)
207. 关闭设备(如果需要)
21
22应用参考 [hwtimer_test] (/examples/test/hwtimer\_test.c)
23
24## 驱动编写指南
25
26### 操作接口
27
28```
29struct rt_hwtimer_ops
30{
31    void (*init)(struct rt_hwtimer_device *timer, rt_uint32_t state);
32    rt_err_t (*start)(struct rt_hwtimer_device *timer, rt_uint32_t cnt, rt_hwtimer_mode_t mode);
33    void (*stop)(struct rt_hwtimer_device *timer);
34    rt_uint32_t (*count_get)(struct rt_hwtimer_device *timer);
35    rt_err_t (*control)(struct rt_hwtimer_device *timer, rt_uint32_t cmd, void *args);
36};
37```
38
39* init - state <1 打开设备 0 关闭设备>
40* start - cnt <超时值> - mode <单次/周期>
41* stop - <停止计数>
42* count_get - <读取计数器值>
43* control - <设置计数频率 >
44
45### 定时器特征信息
46
47```
48struct rt_hwtimer_info
49{
50    rt_int32_t maxfreq;
51    rt_int32_t minfreq;
52    rt_uint32_t maxcnt;
53    rt_uint8_t  cntmode;
54 };
55```
56
57* maxfreq <设备支持的最大计数频率>
58* minfreq <设备支持的最小计数频率>
59* maxcnt  <计数器最大计数值>
60* cntmode <递增计数/递减计数>
61
62### 注册设备
63
64```
65static rt_hwtimer_t _timer0;
66int stm32_hwtimer_init(void)
67{
68    _timer0.info = &_info;
69    _timer0.ops  = &_ops;
70
71    rt_device_hwtimer_register(&_timer0, "timer0", TIM2);
72
73    return 0;
74}
75```
76
77### 定时器中断
78
79```
80void timer_irq_handler(void)
81{
82    //其它操作
83
84    rt_device_hwtimer_isr(&_timer0);
85}
86```
87
88## 注意事项
89
90**可能出现定时误差**
91
92误差原因:
93
94假设计数器最大值0xFFFF,计数频率1Mhz,定时时间1秒又1微秒。
95
96由于定时器一次最多只能计时到65535us,对于1000001us的定时要求。
97可以50000us定时20次完成,此时将会出现计算误差1us。
98