timer.c (1789B)
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 17 #include "timer.h" 18 #include <stdatomic.h> 19 20 static atomic_uint_least32_t current_time = 0; 21 static atomic_uint_least32_t async_tick_amount = 0; 22 static atomic_uint_least32_t access_counter = 0; 23 24 void simulate_async_tick(uint32_t t) { 25 async_tick_amount = t; 26 } 27 28 uint32_t timer_read_internal(void) { 29 return current_time; 30 } 31 32 uint32_t current_access_counter(void) { 33 return access_counter; 34 } 35 36 void reset_access_counter(void) { 37 access_counter = 0; 38 } 39 40 void timer_init(void) { 41 current_time = 0; 42 async_tick_amount = 0; 43 access_counter = 0; 44 } 45 46 void timer_clear(void) { 47 current_time = 0; 48 async_tick_amount = 0; 49 access_counter = 0; 50 } 51 52 uint16_t timer_read(void) { 53 return (uint16_t)timer_read32(); 54 } 55 56 uint32_t timer_read32(void) { 57 if (access_counter++ > 0) { 58 current_time += async_tick_amount; 59 } 60 return current_time; 61 } 62 63 void set_time(uint32_t t) { 64 current_time = t; 65 access_counter = 0; 66 } 67 68 void advance_time(uint32_t ms) { 69 current_time += ms; 70 access_counter = 0; 71 } 72 73 void wait_ms(uint32_t ms) { 74 advance_time(ms); 75 }