nrf52/acomp.rs
1// Licensed under the Apache License, Version 2.0 or the MIT License.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3// Copyright Tock Contributors 2022.
4
5//! Analog Comparator Peripheral Driver, for nrf52
6//!
7//! Partially based on sam4l implementation of an analog comparator.
8//!
9//! The comparator (COMP) compares an input voltage (VIN+) against a second input voltage (VIN-). VIN+ can
10//! be derived from an analog input pin (AIN0-AIN7). VIN- can be derived from multiple sources depending on
11//! the operation mode of the comparator.
12//!
13//! Main features of the comparator are:
14//! - Input range from 0 V to VDD
15//! - Single-ended mode
16//! - Fully flexible hysteresis using a 64-level reference ladder
17//! - Differential mode
18//! - Configurable 50 mV hysteresis
19//! - Reference inputs (VREF):
20//! - VDD
21//! - External reference from AIN0 to AIN7 (between 0 V and VDD)
22//! - Internal references 1.2 V, 1.8 V and 2.4 V
23//! - Three speed/power consumption modes: low-power, normal and high-speed
24//! - Single-pin capacitive sensor support
25//! - Event generation on output changes
26
27use kernel::ErrorCode;
28use kernel::hil::analog_comparator;
29use kernel::utilities::StaticRef;
30use kernel::utilities::cells::OptionalCell;
31use tock_registers_v0::interfaces::{Readable, Writeable};
32use tock_registers_v0::registers::{ReadOnly, ReadWrite, WriteOnly};
33use tock_registers_v0::{register_bitfields, register_structs};
34
35/// Only one channel
36#[derive(Copy, Clone, Debug)]
37#[repr(u8)]
38pub enum ChannelNumber {
39 AC0 = 0x00,
40}
41
42/// Analog comparator channels.
43///
44/// The nrf52840 only has one analog comparator, so it does need channels
45/// However, the HIL was designed to support having multiple comparators, each
46/// one with a separate channel. So we create a dummy channel with only
47/// one possible value to represent this.
48/// Code for channels is based on Sam4l implementation
49pub struct Channel {
50 _chan_num: u32,
51}
52
53/// Initialization of an AC channel.
54impl Channel {
55 /// Create a new AC channel.
56 ///
57 /// - `channel`: Channel enum representing the channel number
58 pub const fn new(channel: ChannelNumber) -> Channel {
59 Channel {
60 _chan_num: (channel as u32) & 0x0F,
61 }
62 }
63}
64
65register_structs! {
66 pub CompRegisters {
67 /// TASK REGISTERS
68 /// Trigger task by writing 1
69 /// start comparator. Needed before comparator does anything.
70 /// After start, triggers events_ready
71 (0x000 => tasks_start: WriteOnly<u32>),
72 /// stop comparator
73 (0x004 => tasks_stop: WriteOnly<u32>),
74 /// sample comparator value
75 /// This triggers an update to RESULT register
76 /// This task doesn't do anything if comparator hasn't
77 /// been started yet.
78 (0x008 => tasks_sample: WriteOnly<u32>),
79 (0x00c => _reserved0),
80
81 /// EVENT REGISTERS
82 /// EVENTS: Can clear by writing 0, occured by 1
83 /// COMP is ready to go after start task
84 (0x100 => events_ready: ReadWrite<u32>),
85 /// Cross from high to low
86 (0x104 => events_down: ReadWrite<u32>),
87 /// cross from low to high
88 (0x108 => events_up: ReadWrite<u32>),
89 /// either events_up or events_down
90 (0x10c => events_cross: ReadWrite<u32>),
91 (0x110 => _reserved1),
92
93 /// Used to link tasks to events in hardware itself
94 /// Pretty much unused.
95 (0x200 => shorts: ReadWrite<u32>),
96 (0x204 => _reserved2),
97
98 /// Used to enable and disable interrupts
99 (0x300 => inten: ReadWrite<u32, InterruptEnable::Register>),
100 /// An alternate way to enable and disable interrupts
101 (0x304 => intenset: ReadWrite<u32>),
102 (0x308 => intenclr: ReadWrite<u32>),
103 (0x30c => _reserved3),
104
105 /// holds result after sampling comparison
106 (0x400 => result: ReadOnly<u32, ComparisonResult::Register>),
107 (0x404 => _reserved4),
108
109 /// Write to enable comparator. Do this after you've set all other settings
110 (0x500 => enable: ReadWrite<u32, Enable::Register>),
111 /// select VIN+
112 (0x504 => psel: ReadWrite<u32, PinSelect::Register>),
113 /// choose where you get VIN- from
114 (0x508 => refsel: ReadWrite<u32, ReferenceSelect::Register>),
115 /// choose which pin to use from VIN-
116 (0x50c => extrefsel: ReadWrite<u32, ExternalRefSelect::Register>),
117 (0x510 => _reserved5),
118
119 /// Hysteresis configuration (single-ended mode)
120 (0x530 => th: ReadWrite<u32>),
121 /// Choose between single ended and differential, and also speed/power
122 (0x534 => mode: ReadWrite<u32, Mode::Register>),
123 /// Hysteresis configuration (differential mode)
124 (0x538 => hyst: ReadWrite<u32, Hysteresis::Register>),
125 /// nrf52832 has one more register that was not included here because it's not used
126 /// and it doesn't exist on nrf52840
127 (0x53c => @END),
128 }
129}
130
131register_bitfields! [
132 u32,
133 InterruptEnable [
134 /// enable / disable interrupts for each event
135 READY OFFSET(0) NUMBITS(1) [],
136 DOWN OFFSET(1) NUMBITS(1) [],
137 UP OFFSET(2) NUMBITS(1) [],
138 CROSS OFFSET(3) NUMBITS(1) []
139 ],
140 ComparisonResult [
141 RESULT OFFSET(1) NUMBITS(1) [
142 /// VIN+ < VIN-
143 Below = 0,
144 /// VIN+ > VIN-
145 Above = 1
146 ]
147 ],
148 Enable [
149 ENABLE OFFSET(0) NUMBITS(2) [
150 Disabled = 0,
151 Enabled = 2
152 ]
153 ],
154 /// Select VIN+ input pin
155 PinSelect [
156 PinSelect OFFSET(0) NUMBITS(3) [
157 AnalogInput0 = 0,
158 AnalogInput1 = 1,
159 AnalogInput2 = 2,
160 AnalogInput3 = 3,
161 AnalogInput4 = 4,
162 AnalogInput5 = 5,
163 AnalogInput6 = 6,
164 AnalogInput7 = 7
165 ]
166 ],
167 /// Select reference source if in Single-Ended mode
168 ReferenceSelect [
169 ReferenceSelect OFFSET(0) NUMBITS(3) [
170 /// Reference voltage = 1.2V VDD >= 1.7
171 Internal1V2 = 0,
172 /// VREF = 1.8V (VDD >= VREF + .2V)
173 Internal1V8 = 1,
174 /// VREF = 2.4V (VDD >= VREF + .2V)
175 Internal2V4 = 2,
176 /// VREF = VDD
177 VDD = 4,
178 /// Select another pin as a reference
179 /// (VDD >= VREF >= AREFMIN)
180 AnalogReference = 5
181 ]
182 ],
183 /// If in diff mode, or single-ended mode with an analog reference,
184 /// use the pin specified here for VIN-
185 ExternalRefSelect[
186 ExternalRefSelect OFFSET(0) NUMBITS(3) [
187 AnalogRef0 = 0,
188 AnalogRef1 = 1,
189 /// The last six values are only valid on nrf52840, not nrf52832
190 AnalogRef2 = 2,
191 AnalogRef3 = 3,
192 AnalogRef4 = 4,
193 AnalogRef5 = 5,
194 AnalogRef6 = 6,
195 AnalogRef7 = 7
196 ]
197 ],
198 Mode[
199 /// Controls power usage and correspondingly speed of comparator
200 SpeedAndPower OFFSET(0) NUMBITS(3) [
201 Low = 0,
202 Normal = 1,
203 High = 2
204 ],
205 OperatingMode OFFSET(8) NUMBITS(1) [
206 SingleEnded = 0,
207 Differential = 1
208 ]
209 ],
210 /// HYST register for hysteresis in diff mode
211 /// Turns on 50mV hysteresis
212 Hysteresis [
213 Hysteresis OFFSET(0) NUMBITS(1)[]
214 ]
215];
216
217pub struct Comparator<'a> {
218 registers: StaticRef<CompRegisters>,
219 client: OptionalCell<&'a dyn analog_comparator::Client>,
220}
221
222impl Comparator<'_> {
223 pub const fn new(registers: StaticRef<CompRegisters>) -> Self {
224 Comparator {
225 registers,
226 client: OptionalCell::empty(),
227 }
228 }
229
230 /// Enables comparator
231 /// Uses differential mode, with no hysteresis, and normal speed and power
232 /// VIN+ = AIN5 and VIN- = AIN0
233 fn enable(&self) {
234 // Checks if it's already enabled
235 // Assumes no one else is writing to comp registers directly
236 if self
237 .registers
238 .enable
239 .any_matching_bits_set(Enable::ENABLE::Enabled)
240 {
241 return;
242 }
243
244 // Set mode to Differential
245 // Differential and single ended are pretty much the same,
246 // except single-ended gives more options for input and
247 // uses a ref ladder for hysteresis instead of a set voltage
248 self.registers
249 .mode
250 .write(Mode::OperatingMode::Differential + Mode::SpeedAndPower::Normal);
251 // VIN+ = Pin 0
252 self.registers
253 .psel
254 .write(PinSelect::PinSelect::AnalogInput5);
255 // VIN- = Pin 1
256 self.registers
257 .extrefsel
258 .write(ExternalRefSelect::ExternalRefSelect::AnalogRef0);
259 // Disable hysteresis
260 self.registers.hyst.write(Hysteresis::Hysteresis::CLEAR);
261
262 self.registers.enable.write(Enable::ENABLE::Enabled);
263 // start comparator
264 self.registers.events_ready.set(0);
265 self.registers.tasks_start.set(1);
266 // wait for comparator to be ready
267 // delay is on order of 3 microseconds so spin wait is OK
268 while self.registers.events_ready.get() == 0 {}
269 }
270
271 fn disable(&self) {
272 // stop comparator
273 self.registers.tasks_stop.set(1);
274 // completely turn comparator off
275 self.registers.enable.write(Enable::ENABLE::Disabled);
276 }
277
278 /// Handles upward crossing events (when VIN+ becomes greater than VIN-)
279 pub fn handle_interrupt(&self) {
280 // HIL only cares about upward crossing interrupts
281 // VIN+ crossed VIN-
282 if self.registers.events_up.get() == 1 {
283 // Clear event
284 self.registers.events_up.set(0);
285 self.client.map(|client| {
286 // Only one channel (0)
287 client.fired(0);
288 });
289 }
290 }
291}
292
293impl<'a> analog_comparator::AnalogComparator<'a> for Comparator<'a> {
294 type Channel = Channel;
295
296 /// Starts comparison on only channel
297 /// This enables comparator and interrupts
298 fn start_comparing(&self, _: &Self::Channel) -> Result<(), ErrorCode> {
299 self.enable();
300
301 // Enable only up interrupt (If VIN+ crosses VIN-)
302 self.registers.inten.write(InterruptEnable::UP::SET);
303
304 Ok(())
305 }
306
307 /// Stops comparing and disables comparator
308 fn stop_comparing(&self, _: &Self::Channel) -> Result<(), ErrorCode> {
309 // Disables interrupts
310 self.registers.inten.set(0);
311 // Stops comparison
312 self.registers.tasks_stop.set(1);
313
314 self.disable();
315 Ok(())
316 }
317
318 /// Performs a single comparison between VIN+ and VIN-
319 /// Returns true if vin+ > vin-
320 /// Enables comparator if not enabled, to disable call stop comparing
321 fn comparison(&self, _: &Self::Channel) -> bool {
322 self.enable();
323
324 // Signals to update Result register
325 self.registers.tasks_sample.set(1);
326
327 // Returns 1 (true) if vin+ > vin-
328 self.registers.result.get() == 1
329 }
330
331 fn set_client(&self, client: &'a dyn analog_comparator::Client) {
332 self.client.set(client);
333 }
334}