1 /*
2  * Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include "pico.h"
8 
9 // For MHZ definitions etc
10 #include "hardware/clocks.h"
11 
12 #include "hardware/platform_defs.h"
13 #include "hardware/regs/xosc.h"
14 #include "hardware/xosc.h"
15 
16 #if XOSC_MHZ < 1 || XOSC_MHZ > 50
17 #error XOSC_MHZ must be in the range 1-50
18 #endif
19 
20 #define STARTUP_DELAY (((((XOSC_MHZ * PICO_MHZ) / 1000) + 128) / 256) * PICO_XOSC_STARTUP_DELAY_MULTIPLIER)
21 
22 // The DELAY field in xosc_hw->startup is 14 bits wide.
23 #if STARTUP_DELAY >= (1 << 13)
24 #error PICO_XOSC_STARTUP_DELAY_MULTIPLIER is too large: XOSC STARTUP.DELAY must be < 8192
25 #endif
26 
xosc_init(void)27 void xosc_init(void) {
28     // Assumes 1-15 MHz input, checked above.
29     xosc_hw->ctrl = XOSC_CTRL_FREQ_RANGE_VALUE_1_15MHZ;
30 
31     // Set xosc startup delay
32     xosc_hw->startup = STARTUP_DELAY;
33 
34     // Set the enable bit now that we have set freq range and startup delay
35     hw_set_bits(&xosc_hw->ctrl, XOSC_CTRL_ENABLE_VALUE_ENABLE << XOSC_CTRL_ENABLE_LSB);
36 
37     // Wait for XOSC to be stable
38     while(!(xosc_hw->status & XOSC_STATUS_STABLE_BITS));
39 }
40 
xosc_disable(void)41 void xosc_disable(void) {
42     uint32_t tmp = xosc_hw->ctrl;
43     tmp &= (~XOSC_CTRL_ENABLE_BITS);
44     tmp |= (XOSC_CTRL_ENABLE_VALUE_DISABLE << XOSC_CTRL_ENABLE_LSB);
45     xosc_hw->ctrl = tmp;
46     // Wait for stable to go away
47     while(xosc_hw->status & XOSC_STATUS_STABLE_BITS);
48 }
49 
xosc_dormant(void)50 void xosc_dormant(void) {
51     // WARNING: This stops the xosc until woken up by an irq
52     xosc_hw->dormant = XOSC_DORMANT_VALUE_DORMANT;
53     // Wait for it to become stable once woken up
54     while(!(xosc_hw->status & XOSC_STATUS_STABLE_BITS));
55 }
56