drv_wdt.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (c) 2006-2021, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2020-08-18 ylz0923 first version
  9. * 2021-08-12 chenyingchun optimize wdt_control arg usage
  10. */
  11. #include <board.h>
  12. #include <rtdevice.h>
  13. #include <nrfx_wdt.h>
  14. #ifdef RT_USING_WDT
  15. struct nrf5x_wdt_obj
  16. {
  17. rt_watchdog_t watchdog;
  18. nrfx_wdt_t wdt;
  19. nrfx_wdt_channel_id ch;
  20. rt_uint16_t is_start;
  21. };
  22. static struct nrf5x_wdt_obj nrf5x_wdt = {
  23. .wdt = NRFX_WDT_INSTANCE(0),
  24. };
  25. static nrfx_wdt_config_t nrf5x_wdt_cfg = NRFX_WDT_DEFAULT_CONFIG;
  26. static struct rt_watchdog_ops ops;
  27. static rt_err_t wdt_init(rt_watchdog_t *wdt)
  28. {
  29. return RT_EOK;
  30. }
  31. static rt_err_t wdt_control(rt_watchdog_t *wdt, int cmd, void *arg)
  32. {
  33. switch (cmd)
  34. {
  35. /* feed the watchdog */
  36. case RT_DEVICE_CTRL_WDT_KEEPALIVE:
  37. nrfx_wdt_feed(&nrf5x_wdt.wdt);
  38. break;
  39. /* set watchdog timeout */
  40. case RT_DEVICE_CTRL_WDT_SET_TIMEOUT:
  41. nrf5x_wdt_cfg.reload_value = (*((rt_uint32_t*)arg)) * 1000;
  42. break;
  43. case RT_DEVICE_CTRL_WDT_GET_TIMEOUT:
  44. *((rt_uint32_t*)arg) = nrf5x_wdt_cfg.reload_value;
  45. break;
  46. case RT_DEVICE_CTRL_WDT_START:
  47. if (nrf5x_wdt.is_start != 1)
  48. {
  49. nrfx_wdt_init(&nrf5x_wdt.wdt, &nrf5x_wdt_cfg, RT_NULL);
  50. nrfx_wdt_channel_alloc(&nrf5x_wdt.wdt, &nrf5x_wdt.ch);
  51. nrfx_wdt_enable(&nrf5x_wdt.wdt);
  52. nrf5x_wdt.is_start = 1;
  53. }
  54. break;
  55. default:
  56. return -RT_ERROR;
  57. }
  58. return RT_EOK;
  59. }
  60. int rt_wdt_init(void)
  61. {
  62. nrf5x_wdt.is_start = 0;
  63. ops.init = &wdt_init;
  64. ops.control = &wdt_control;
  65. nrf5x_wdt.watchdog.ops = &ops;
  66. /* register watchdog device */
  67. if (rt_hw_watchdog_register(&nrf5x_wdt.watchdog, "wdt", RT_DEVICE_FLAG_DEACTIVATE, RT_NULL) != RT_EOK)
  68. {
  69. return -RT_ERROR;
  70. }
  71. return RT_EOK;
  72. }
  73. INIT_BOARD_EXPORT(rt_wdt_init);
  74. static int wdt_sample(int argc, char *argv[])
  75. {
  76. rt_uint32_t timeout = 2; /* 溢出时间,单位:秒*/
  77. rt_device_t wdt = rt_device_find("wdt");
  78. rt_device_init(wdt);
  79. rt_device_control(wdt, RT_DEVICE_CTRL_WDT_SET_TIMEOUT, &timeout);
  80. rt_device_control(wdt, RT_DEVICE_CTRL_WDT_START, RT_NULL);
  81. }
  82. MSH_CMD_EXPORT(wdt_sample, wdt sample);
  83. #endif /* RT_USING_WDT */