platformTimer.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #include "platformTimer.h"
  2. uint32_t platformUptimeMs(void)
  3. {
  4. if (1000 == luat_mcu_hz())
  5. return (uint32_t)luat_mcu_ticks();
  6. uint32_t tick = 0;
  7. tick = luat_mcu_ticks() * 1000;
  8. return (uint32_t)((tick + luat_mcu_ticks() - 1) / luat_mcu_ticks());
  9. }
  10. /**
  11. * @brief 初始化定时器
  12. *
  13. * @param platformTimer
  14. */
  15. void platformTimerInit(platformTimer_t *platformTimer)
  16. {
  17. platformTimer->time = 0;
  18. platformTimer->timeOut = 0;
  19. }
  20. /**
  21. * @brief 添加计数时间
  22. *
  23. * @param platformTimer
  24. * @param timeout
  25. */
  26. void platformTimerCutdown(platformTimer_t *platformTimer, uint32_t timeout)
  27. {
  28. platformTimer->timeOut = timeout;
  29. platformTimer->time = platformUptimeMs();
  30. }
  31. /**
  32. * @brief 计算time还有多长时间超时,考虑了32位溢出判断
  33. *
  34. * @param platformTimer
  35. * @return uint32_t 返回剩余时间,超时返回0
  36. */
  37. uint32_t platformTimerRemain(platformTimer_t *platformTimer)
  38. {
  39. uint32_t tnow = platformUptimeMs();
  40. uint32_t overTime = platformTimer->time + platformTimer->timeOut;
  41. // uint32_t 没有溢出
  42. if (overTime >= platformTimer->time)
  43. {
  44. // tnow溢出,不存在时间超时可能性
  45. if (tnow < platformTimer->time)
  46. return (UINT32_MAX - overTime + tnow + 1);
  47. // tnow没有溢出
  48. return tnow >= overTime ? 0 : (overTime - tnow);
  49. }
  50. // uint32_t 溢出了
  51. // tnow 溢出了
  52. if (tnow < platformTimer->time)
  53. return tnow >= overTime ? 0 : (overTime - tnow + 1);
  54. // tnow 没有溢出
  55. return UINT32_MAX - tnow + overTime + 1;
  56. }