Chris Mumford | c62c9f3 | 2022-11-01 17:40:08 +0000 | [diff] [blame] | 1 | // Copyright 2022 The Pigweed Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); you may not |
| 4 | // use this file except in compliance with the License. You may obtain a copy of |
| 5 | // the License at |
| 6 | // |
| 7 | // https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 | // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 | // License for the specific language governing permissions and limitations under |
| 13 | // the License. |
| 14 | |
| 15 | #include "pw_spin_delay/delay.h" |
| 16 | |
| 17 | #include <cstddef> |
| 18 | #include <cstdint> |
| 19 | |
| 20 | #include "clock_config.h" |
| 21 | #include "fsl_common.h" |
| 22 | #include "fsl_utick.h" |
| 23 | |
| 24 | namespace pw::spin_delay { |
| 25 | |
| 26 | namespace { |
| 27 | |
| 28 | constexpr uint32_t kTickMicros = 1000; // Every 1 ms. |
| 29 | bool s_initialized = false; |
| 30 | volatile uint32_t s_msec_count = 0; |
| 31 | |
Chris Mumford | a6288f0 | 2023-01-04 20:41:28 +0000 | [diff] [blame] | 32 | void UTickCallback(void) { s_msec_count++; } |
Chris Mumford | c62c9f3 | 2022-11-01 17:40:08 +0000 | [diff] [blame] | 33 | |
| 34 | void InitTickTimer() { |
| 35 | s_initialized = true; |
| 36 | UTICK_Init(UTICK0); |
| 37 | UTICK_SetTick(UTICK0, kUTICK_Repeat, kTickMicros, UTickCallback); |
| 38 | } |
| 39 | |
| 40 | } // namespace |
| 41 | |
| 42 | void WaitMillis(size_t delay_ms) { |
| 43 | SDK_DelayAtLeastUs(delay_ms * 1000U, BOARD_BOOTCLOCKRUN_CORE_CLOCK); |
| 44 | } |
| 45 | |
| 46 | uint32_t Millis() { |
| 47 | if (!s_initialized) { |
| 48 | InitTickTimer(); |
| 49 | } |
| 50 | return s_msec_count; |
| 51 | } |
| 52 | |
Chris Mumford | a6288f0 | 2023-01-04 20:41:28 +0000 | [diff] [blame] | 53 | uint64_t Micros() { |
Chris Mumford | c62c9f3 | 2022-11-01 17:40:08 +0000 | [diff] [blame] | 54 | if (!s_initialized) { |
| 55 | InitTickTimer(); |
| 56 | } |
Chris Mumford | a6288f0 | 2023-01-04 20:41:28 +0000 | [diff] [blame] | 57 | return static_cast<uint64_t>(s_msec_count) * 1000; |
Chris Mumford | c62c9f3 | 2022-11-01 17:40:08 +0000 | [diff] [blame] | 58 | } |
| 59 | |
| 60 | } // namespace pw::spin_delay |