hwtimer_sample.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * 程序清单:这是一个 hwtimer 设备使用例程
  3. * 例程导出了 hwtimer_sample 命令到控制终端
  4. * 命令调用格式:hwtimer_sample
  5. * 程序功能:硬件定时器超时回调函数周期性的打印当前tick值,2次tick值之差换算为时间等同于定时时间值。
  6. */
  7. #include <rtthread.h>
  8. #include <rtdevice.h>
  9. #define HWTIMER_DEV_NAME "timer00" /* 定时器名称 */
  10. /* 定时器超时回调函数 */
  11. static rt_err_t timeout_cb(rt_device_t dev, rt_size_t size)
  12. {
  13. rt_kprintf("this is hwtimer timeout callback fucntion!\n");
  14. rt_kprintf("tick is :%d !\n", rt_tick_get());
  15. return 0;
  16. }
  17. static int hwtimer_sample(int argc, char *argv[])
  18. {
  19. rt_err_t ret = RT_EOK;
  20. rt_hwtimerval_t timeout_s; /* 定时器超时值 */
  21. rt_device_t hw_dev = RT_NULL; /* 定时器设备句柄 */
  22. rt_hwtimer_mode_t mode; /* 定时器模式 */
  23. rt_uint32_t freq = 10000; /* 计数频率 */
  24. /* 查找定时器设备 */
  25. hw_dev = rt_device_find(HWTIMER_DEV_NAME);
  26. if (hw_dev == RT_NULL)
  27. {
  28. rt_kprintf("hwtimer sample run failed! can't find %s device!\n", HWTIMER_DEV_NAME);
  29. return RT_ERROR;
  30. }
  31. /* 以读写方式打开设备 */
  32. ret = rt_device_open(hw_dev, RT_DEVICE_OFLAG_RDWR);
  33. if (ret != RT_EOK)
  34. {
  35. rt_kprintf("open %s device failed!\n", HWTIMER_DEV_NAME);
  36. return ret;
  37. }
  38. /* 设置超时回调函数 */
  39. rt_device_set_rx_indicate(hw_dev, timeout_cb);
  40. /* 设置计数频率(若未设置该项,默认为1Mhz 或 支持的最小计数频率) */
  41. rt_device_control(hw_dev, HWTIMER_CTRL_FREQ_SET, &freq);
  42. /* 设置模式为周期性定时器(若未设置,默认是HWTIMER_MODE_ONESHOT)*/
  43. mode = HWTIMER_MODE_PERIOD;
  44. ret = rt_device_control(hw_dev, HWTIMER_CTRL_MODE_SET, &mode);
  45. if (ret != RT_EOK)
  46. {
  47. rt_kprintf("set mode failed! ret is :%d\n", ret);
  48. return ret;
  49. }
  50. /* 设置定时器超时值为5s并启动定时器 */
  51. timeout_s.sec = 5; /* 秒 */
  52. timeout_s.usec = 0; /* 微秒 */
  53. if (rt_device_write(hw_dev, 0, &timeout_s, sizeof(timeout_s)) != sizeof(timeout_s))
  54. {
  55. rt_kprintf("set timeout value failed\n");
  56. return RT_ERROR;
  57. }
  58. /* 延时3500ms */
  59. rt_thread_mdelay(3500);
  60. /* 读取定时器当前值 */
  61. rt_device_read(hw_dev, 0, &timeout_s, sizeof(timeout_s));
  62. rt_kprintf("Read: Sec = %d, Usec = %d\n", timeout_s.sec, timeout_s.usec);
  63. return ret;
  64. }
  65. /* 导出到 msh 命令列表中 */
  66. MSH_CMD_EXPORT(hwtimer_sample, hwtimer sample);