platformTimer.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "platformTimer.h"
  2. // Ryan别的包也有
  3. #define __weak __attribute__((weak)) // 防止函数重定义, gcc / ARM编译器有效 IAR可以注释此行
  4. /**
  5. * @brief 自系统启动以来的毫秒时间戳
  6. *
  7. * @return uint32_t
  8. */
  9. __weak uint32_t platformUptimeMs(void)
  10. {
  11. #if (RT_TICK_PER_SECOND == 1000)
  12. return (uint32_t)rt_tick_get();
  13. #else
  14. rt_tick_t tick = 0u;
  15. tick = rt_tick_get() * 1000;
  16. return (uint32_t)((tick + RT_TICK_PER_SECOND - 1) / RT_TICK_PER_SECOND);
  17. #endif
  18. }
  19. /**
  20. * @brief 初始化定时器,没有使用,
  21. * timer结构体比较简单,没有做init和destory。看后面需求
  22. *
  23. * @param platformTimer
  24. */
  25. __weak void platformTimerInit(platformTimer_t *platformTimer)
  26. {
  27. platformTimer->time = 0;
  28. platformTimer->timeOut = 0;
  29. }
  30. /**
  31. * @brief 添加计数时间
  32. *
  33. * @param platformTimer
  34. * @param timeout
  35. */
  36. __weak void platformTimerCutdown(platformTimer_t *platformTimer, uint32_t timeout)
  37. {
  38. platformTimer->timeOut = timeout;
  39. platformTimer->time = platformUptimeMs();
  40. }
  41. /**
  42. * @brief 计算time还有多长时间超时,考虑了32位溢出判断
  43. *
  44. * @param platformTimer
  45. * @return uint32_t 返回剩余时间,超时返回0
  46. */
  47. __weak uint32_t platformTimerRemain(platformTimer_t *platformTimer)
  48. {
  49. uint32_t tnow = platformUptimeMs();
  50. uint32_t overTime = platformTimer->time + platformTimer->timeOut;
  51. // uint32_t 没有溢出
  52. if (overTime >= platformTimer->time)
  53. {
  54. // tnow溢出,时间必然已经超时
  55. if (tnow < platformTimer->time)
  56. // return (UINT32_MAX - overTime + tnow + 1);
  57. return 0;
  58. // tnow没有溢出
  59. return tnow >= overTime ? 0 : (overTime - tnow);
  60. }
  61. // uint32_t 溢出了
  62. // tnow 溢出了
  63. if (tnow < platformTimer->time)
  64. return tnow >= overTime ? 0 : (overTime - tnow + 1);
  65. // tnow 没有溢出
  66. return UINT32_MAX - tnow + overTime + 1;
  67. }