timer.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /* Copyright 2017 Fred Sundvik
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. #include "timer.h"
  17. #include <stdatomic.h>
  18. static atomic_uint_least32_t current_time = 0;
  19. static atomic_uint_least32_t async_tick_amount = 0;
  20. static atomic_uint_least32_t access_counter = 0;
  21. void simulate_async_tick(uint32_t t) {
  22. async_tick_amount = t;
  23. }
  24. uint32_t timer_read_internal(void) {
  25. return current_time;
  26. }
  27. uint32_t current_access_counter(void) {
  28. return access_counter;
  29. }
  30. void reset_access_counter(void) {
  31. access_counter = 0;
  32. }
  33. void timer_init(void) {
  34. current_time = 0;
  35. async_tick_amount = 0;
  36. access_counter = 0;
  37. }
  38. void timer_clear(void) {
  39. current_time = 0;
  40. async_tick_amount = 0;
  41. access_counter = 0;
  42. }
  43. uint16_t timer_read(void) {
  44. return (uint16_t)timer_read32();
  45. }
  46. uint32_t timer_read32(void) {
  47. if (access_counter++ > 0) {
  48. current_time += async_tick_amount;
  49. }
  50. return current_time;
  51. }
  52. uint16_t timer_elapsed(uint16_t last) {
  53. return TIMER_DIFF_16(timer_read(), last);
  54. }
  55. uint32_t timer_elapsed32(uint32_t last) {
  56. return TIMER_DIFF_32(timer_read32(), last);
  57. }
  58. void set_time(uint32_t t) {
  59. current_time = t;
  60. access_counter = 0;
  61. }
  62. void advance_time(uint32_t ms) {
  63. current_time += ms;
  64. access_counter = 0;
  65. }
  66. void wait_ms(uint32_t ms) {
  67. advance_time(ms);
  68. }