hwtimer_sample.c 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. #include <rtthread.h>
  17. #include <rtdevice.h>
  18. #define HWTIMER_DEV_NAME "timer0"
  19. /* 定时器超时回调函数 */
  20. static rt_err_t timeout_cb(rt_device_t dev, rt_size_t size)
  21. {
  22. rt_kprintf("this is hwtimer timeout callback fucntion!\n");
  23. rt_kprintf("tick is :%d !\n", rt_tick_get());
  24. return 0;
  25. }
  26. static int hwtimer_sample(int argc, char *argv[])
  27. {
  28. rt_err_t ret = RT_EOK;
  29. rt_hwtimerval_t timeout_s;
  30. rt_device_t hw_dev = RT_NULL;
  31. rt_hwtimer_mode_t mode; /* 定时器模式 */
  32. rt_uint32_t freq = 10000; /* 计数频率 */
  33. /* 查找定时器设备 */
  34. hw_dev = rt_device_find(HWTIMER_DEV_NAME);
  35. if (hw_dev == RT_NULL)
  36. {
  37. rt_kprintf("hwtimer sample run failed! can't find %s device!\n", HWTIMER_DEV_NAME);
  38. return RT_ERROR;
  39. }
  40. /* 打开设备 */
  41. ret = rt_device_open(hw_dev, RT_DEVICE_OFLAG_RDWR);
  42. if (ret != RT_EOK)
  43. {
  44. rt_kprintf("open %s device failed!\n", HWTIMER_DEV_NAME);
  45. return ret;
  46. }
  47. /* 设置超时回调函数 */
  48. rt_device_set_rx_indicate(hw_dev, timeout_cb);
  49. /* 设置计数频率(默认1Mhz或支持的最小计数频率) */
  50. ret = rt_device_control(hw_dev, HWTIMER_CTRL_FREQ_SET, &freq);
  51. if (ret != RT_EOK)
  52. {
  53. rt_kprintf("set frequency failed! ret is :%d\n", ret);
  54. return ret;
  55. }
  56. /* 设置模式为周期性定时器 */
  57. mode = HWTIMER_MODE_PERIOD;
  58. ret = rt_device_control(hw_dev, HWTIMER_CTRL_MODE_SET, &mode);
  59. if (ret != RT_EOK)
  60. {
  61. rt_kprintf("set mode failed! ret is :%d\n", ret);
  62. return ret;
  63. }
  64. /* 设置定时器超时值为5s并启动定时器 */
  65. timeout_s.sec = 5; /* 秒 */
  66. timeout_s.usec = 0; /* 微秒 */
  67. if (rt_device_write(hw_dev, 0, &timeout_s, sizeof(timeout_s)) != sizeof(timeout_s))
  68. {
  69. rt_kprintf("set timeout value failed\n");
  70. return RT_ERROR;
  71. }
  72. /* 延时3500ms */
  73. rt_thread_mdelay(3500);
  74. /* 读取定时器当前值 */
  75. rt_device_read(hw_dev, 0, &timeout_s, sizeof(timeout_s));
  76. rt_kprintf("Read: Sec = %d, Usec = %d\n", timeout_s.sec, timeout_s.usec);
  77. return ret;
  78. }
  79. /* 导出到 msh 命令列表中 */
  80. MSH_CMD_EXPORT(hwtimer_sample, hwtimer sample);