blob: f1a579a763ff71dd446841a23c59cdfa95ff5c67 [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
Chris Mumforda6288f02023-01-04 20:41:28 +000032void UTickCallback(void) { s_msec_count++; }
Chris Mumfordc62c9f32022-11-01 17:40:08 +000033
34void InitTickTimer() {
35 s_initialized = true;
36 UTICK_Init(UTICK0);
37 UTICK_SetTick(UTICK0, kUTICK_Repeat, kTickMicros, UTickCallback);
38}
39
40} // namespace
41
42void WaitMillis(size_t delay_ms) {
43 SDK_DelayAtLeastUs(delay_ms * 1000U, BOARD_BOOTCLOCKRUN_CORE_CLOCK);
44}
45
46uint32_t Millis() {
47 if (!s_initialized) {
48 InitTickTimer();
49 }
50 return s_msec_count;
51}
52
Chris Mumforda6288f02023-01-04 20:41:28 +000053uint64_t Micros() {
Chris Mumfordc62c9f32022-11-01 17:40:08 +000054 if (!s_initialized) {
55 InitTickTimer();
56 }
Chris Mumforda6288f02023-01-04 20:41:28 +000057 return static_cast<uint64_t>(s_msec_count) * 1000;
Chris Mumfordc62c9f32022-11-01 17:40:08 +000058}
59
60} // namespace pw::spin_delay