platformTimer.c 1.6 KB

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