platformTimer.c 1.7 KB

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