1+ /*
2+ * Copyright (c) 2006-2018, RT-Thread Development Team
3+ *
4+ * SPDX-License-Identifier: Apache-2.0
5+ *
6+ * Change Logs:
7+ * Date Author Notes
8+ * 2018-11-30 misonyo first implementation.
9+ */
10+ /*
11+ * 程序清单:这是一个 hwtimer 设备使用例程
12+ * 例程导出了 hwtimer_sample 命令到控制终端
13+ * 命令调用格式:hwtimer_sample
14+ * 程序功能:硬件定时器周期性的打印当前tick值,2次tick值之差也就是定时时间。
15+ */
16+
17+ #include <rtthread.h>
18+ #include <rtdevice.h>
19+
20+ #define HWTIMER_DEV_NAME "timer0"
21+
22+ /* 定时器超时回调函数 */
23+ static rt_err_t timeout_cb (rt_device_t dev , rt_size_t size )
24+ {
25+ rt_kprintf ("this is hwtimer timeout callback fucntion!\n" );
26+ rt_kprintf ("tick is :%d !\n" , rt_tick_get ());
27+
28+ return 0 ;
29+ }
30+
31+ static int hwtimer_sample (int argc , char * argv [])
32+ {
33+ rt_err_t ret = RT_EOK ;
34+ rt_hwtimerval_t timeout_s ;
35+ rt_device_t hw_dev = RT_NULL ;
36+ rt_hwtimer_mode_t mode ; /* 定时器模式 */
37+ rt_uint32_t freq = 10000 ; /* 计数频率 */
38+
39+ /* 查找定时器设备 */
40+ hw_dev = rt_device_find (HWTIMER_DEV_NAME );
41+ if (hw_dev == RT_NULL )
42+ {
43+ rt_kprintf ("hwtimer sample run failed! can't find %s device!\n" , HWTIMER_DEV_NAME );
44+ return RT_ERROR ;
45+ }
46+
47+ /* 打开设备 */
48+ ret = rt_device_open (hw_dev , RT_DEVICE_OFLAG_RDWR );
49+ if (ret != RT_EOK )
50+ {
51+ rt_kprintf ("open %s device failed!\n" , HWTIMER_DEV_NAME );
52+ return ret ;
53+ }
54+
55+ /* 设置超时回调函数 */
56+ rt_device_set_rx_indicate (hw_dev , timeout_cb );
57+
58+ /* 设置计数频率(默认1Mhz或支持的最小计数频率) */
59+ ret = rt_device_control (hw_dev , HWTIMER_CTRL_FREQ_SET , & freq );
60+ if (ret != RT_EOK )
61+ {
62+ rt_kprintf ("set frequency failed! ret is :%d\n" , ret );
63+ return ret ;
64+ }
65+
66+ /* 设置模式为周期性定时器 */
67+ mode = HWTIMER_MODE_PERIOD ;
68+ ret = rt_device_control (hw_dev , HWTIMER_CTRL_MODE_SET , & mode );
69+ if (ret != RT_EOK )
70+ {
71+ rt_kprintf ("set mode failed! ret is :%d\n" , ret );
72+ return ret ;
73+ }
74+
75+ /* 设置定时器超时值为5s并启动定时器 */
76+ timeout_s .sec = 5 ; /* 秒 */
77+ timeout_s .usec = 0 ; /* 微秒 */
78+
79+ if (rt_device_write (hw_dev , 0 , & timeout_s , sizeof (timeout_s )) != sizeof (timeout_s ))
80+ {
81+ rt_kprintf ("set timeout value failed\n" );
82+ return RT_ERROR ;
83+ }
84+
85+ /* 延时3500ms */
86+ rt_thread_mdelay (3500 );
87+
88+ /* 读取定时器当前值 */
89+ rt_device_read (hw_dev , 0 , & timeout_s , sizeof (timeout_s ));
90+ rt_kprintf ("Read: Sec = %d, Usec = %d\n" , timeout_s .sec , timeout_s .usec );
91+
92+ return ret ;
93+ }
94+ /* 导出到 msh 命令列表中 */
95+ MSH_CMD_EXPORT (hwtimer_sample , hwtimer sample );
0 commit comments