platformTimer.c 1.6 KB

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