hwtimer_sample.c 2.8 KB

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