platformTimer.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include "platformTimer.h"
  2. uint32_t platformUptimeMs(void)
  3. {
  4. #if (RT_TICK_PER_SECOND == 1000)
  5. return (uint32_t)rt_tick_get();
  6. #else
  7. rt_tick_t tick = 0u;
  8. tick = rt_tick_get() * 1000;
  9. return (uint32_t)((tick + RT_TICK_PER_SECOND - 1) / RT_TICK_PER_SECOND);
  10. #endif
  11. }
  12. /**
  13. * @brief 初始化定时器,没有使用,
  14. * timer结构体比较简单,没有做init和destory。看后面需求
  15. *
  16. * @param platformTimer
  17. */
  18. void platformTimerInit(platformTimer_t *platformTimer)
  19. {
  20. platformTimer->time = 0;
  21. platformTimer->timeOut = 0;
  22. }
  23. /**
  24. * @brief 添加计数时间
  25. *
  26. * @param platformTimer
  27. * @param timeout
  28. */
  29. void platformTimerCutdown(platformTimer_t *platformTimer, uint32_t timeout)
  30. {
  31. platformTimer->timeOut = timeout;
  32. platformTimer->time = platformUptimeMs();
  33. }
  34. /**
  35. * @brief 计算time还有多长时间超时,考虑了32位溢出判断
  36. *
  37. * @param platformTimer
  38. * @return uint32_t 返回剩余时间,超时返回0
  39. */
  40. uint32_t platformTimerRemain(platformTimer_t *platformTimer)
  41. {
  42. uint32_t tnow = platformUptimeMs();
  43. uint32_t overTime = platformTimer->time + platformTimer->timeOut;
  44. // uint32_t 没有溢出
  45. if (overTime >= platformTimer->time)
  46. {
  47. // tnow溢出,时间必然已经超时
  48. if (tnow < platformTimer->time)
  49. // return (UINT32_MAX - overTime + tnow + 1);
  50. return 0;
  51. // tnow没有溢出
  52. return tnow >= overTime ? 0 : (overTime - tnow);
  53. }
  54. // uint32_t 溢出了
  55. // tnow 溢出了
  56. if (tnow < platformTimer->time)
  57. return tnow >= overTime ? 0 : (overTime - tnow + 1);
  58. // tnow 没有溢出
  59. return UINT32_MAX - tnow + overTime + 1;
  60. }