platformTimer.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 将时间设置为0
  14. *
  15. * @param platformTimer
  16. */
  17. void platformTimerInit(platformTimer_t *platformTimer)
  18. {
  19. platformTimer->time = 0;
  20. platformTimer->timeOut = 0;
  21. }
  22. /**
  23. * @brief 添加计数时间
  24. *
  25. * @param platformTimer
  26. * @param timeout
  27. */
  28. void platformTimerCutdown(platformTimer_t *platformTimer, uint32_t timeout)
  29. {
  30. platformTimer->timeOut = timeout;
  31. platformTimer->time = platformUptimeMs();
  32. }
  33. /**
  34. * @brief 计算time还有多长时间超时,考虑了32位溢出判断
  35. *
  36. * @param platformTimer
  37. * @return uint32_t 返回剩余时间,超时返回0
  38. */
  39. uint32_t platformTimerRemain(platformTimer_t *platformTimer)
  40. {
  41. uint32_t tnow = platformUptimeMs();
  42. uint32_t overTime = platformTimer->time + platformTimer->timeOut;
  43. // uint32_t 没有溢出
  44. if (overTime >= platformTimer->time)
  45. {
  46. // tnow溢出,不存在时间超时可能性
  47. if (tnow < platformTimer->time)
  48. return (UINT32_MAX - overTime + tnow + 1);
  49. // tnow没有溢出
  50. return tnow >= overTime ? 0 : (overTime - tnow);
  51. }
  52. // uint32_t 溢出了
  53. // tnow 溢出了
  54. if (tnow < platformTimer->time)
  55. return tnow >= overTime ? 0 : (overTime - tnow + 1);
  56. // tnow 没有溢出
  57. return UINT32_MAX - tnow + overTime + 1;
  58. }