platformTimer.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. *
  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. return 0;
  50. // tnow没有溢出
  51. return tnow >= overTime ? 0 : (overTime - tnow);
  52. }
  53. // uint32_t 溢出了
  54. // tnow 溢出了
  55. if (tnow < platformTimer->time)
  56. return tnow >= overTime ? 0 : (overTime - tnow + 1);
  57. // tnow 没有溢出
  58. return UINT32_MAX - tnow + overTime + 1;
  59. }