platformTimer.c 1.5 KB

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