1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
use embedded_time::rate::Extensions;
use embedded_time::rate::Hertz;
pub trait State {}
pub struct Disabled;
pub struct Enabled {
freq_hz: Hertz,
}
pub struct Dormant;
impl State for Disabled {}
impl State for Enabled {}
impl State for Dormant {}
pub struct RingOscillator<S: State> {
device: rp2040_pac::ROSC,
state: S,
}
impl<S: State> RingOscillator<S> {
fn transition<To: State>(self, state: To) -> RingOscillator<To> {
RingOscillator {
device: self.device,
state,
}
}
pub fn free(self) -> rp2040_pac::ROSC {
self.device
}
}
impl RingOscillator<Disabled> {
pub fn new(dev: rp2040_pac::ROSC) -> Self {
RingOscillator {
device: dev,
state: Disabled,
}
}
pub fn initialize(self) -> RingOscillator<Enabled> {
self.device.ctrl.write(|w| w.enable().enable());
self.transition(Enabled {
freq_hz: 6_500_000u32.Hz(),
})
}
}
impl RingOscillator<Enabled> {
pub fn operating_frequency(&self) -> Hertz {
self.state.freq_hz
}
pub fn disable(self) -> RingOscillator<Disabled> {
self.device.ctrl.modify(|_r, w| w.enable().disable());
self.transition(Disabled)
}
pub fn get_random_bit(&self) -> bool {
self.device.randombit.read().randombit().bit()
}
pub unsafe fn dormant(self) -> RingOscillator<Dormant> {
const ROSC_DORMANT_VALUE: u32 = 0x636f6d61;
self.device.dormant.write(|w| w.bits(ROSC_DORMANT_VALUE));
self.transition(Dormant)
}
}
impl rand_core::RngCore for RingOscillator<Enabled> {
fn next_u32(&mut self) -> u32 {
rand_core::impls::next_u32_via_fill(self)
}
fn next_u64(&mut self) -> u64 {
rand_core::impls::next_u64_via_fill(self)
}
fn fill_bytes(&mut self, dest: &mut [u8]) {
for chunk in dest.iter_mut() {
*chunk = 0_u8;
for _ in 0..8 {
*chunk <<= 1;
*chunk ^= self.get_random_bit() as u8;
}
}
}
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
self.fill_bytes(dest);
Ok(())
}
}