blob: de78ee65431eb67d7311fe5ccebbbf57acc8b678 [file] [log] [blame]
Chris Mumfordc62c9f32022-11-01 17:40:08 +00001// 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
24namespace pw::spin_delay {
25
26namespace {
27
28constexpr uint32_t kTickMicros = 1000; // Every 1 ms.
29bool s_initialized = false;
30volatile uint32_t s_msec_count = 0;
31
32void UTickCallback(void) {
33 // clang-format off
34 s_msec_count++;
35 // clang-format on
36}
37
38void InitTickTimer() {
39 s_initialized = true;
40 UTICK_Init(UTICK0);
41 UTICK_SetTick(UTICK0, kUTICK_Repeat, kTickMicros, UTickCallback);
42}
43
44} // namespace
45
46void WaitMillis(size_t delay_ms) {
47 SDK_DelayAtLeastUs(delay_ms * 1000U, BOARD_BOOTCLOCKRUN_CORE_CLOCK);
48}
49
50uint32_t Millis() {
51 if (!s_initialized) {
52 InitTickTimer();
53 }
54 return s_msec_count;
55}
56
57uint32_t Micros() {
58 if (!s_initialized) {
59 InitTickTimer();
60 }
61 return s_msec_count * 1000;
62}
63
64} // namespace pw::spin_delay