Skip to main content

nrf52/
pwm.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//! PWM driver for nRF52.
6
7use kernel::ErrorCode;
8use kernel::hil;
9use kernel::utilities::StaticRef;
10use tock_registers_v0::interfaces::Writeable;
11use tock_registers_v0::registers::{ReadWrite, WriteOnly};
12use tock_registers_v0::{register_bitfields, register_structs};
13
14register_structs! {
15    pub PwmRegisters {
16        (0x000 => _reserved0),
17        /// Stops PWM pulse generation on all channels at the end of current PWM period
18        (0x004 => tasks_stop: WriteOnly<u32, TASK::Register>),
19        /// Loads the first PWM value on all enabled channels
20        (0x008 => tasks_seqstart: [WriteOnly<u32, TASK::Register>; 2]),
21        /// Steps by one value in the current sequence on all enabled channels if DECODER.MO
22        (0x010 => tasks_nextstep: WriteOnly<u32, TASK::Register>),
23        (0x014 => _reserved1),
24        /// Response to STOP task, emitted when PWM pulses are no longer generated
25        (0x104 => events_stopped: ReadWrite<u32, EVENT::Register>),
26        /// First PWM period started on sequence 0
27        (0x108 => events_seqstarted: [ReadWrite<u32, EVENT::Register>; 2]),
28        /// Emitted at end of every sequence 0, when last value from RAM has been
29        /// applied to the wave counter
30        (0x110 => events_seqend: [ReadWrite<u32, EVENT::Register>; 2]),
31        /// Emitted at the end of each PWM period
32        (0x118 => events_pwmperiodend: ReadWrite<u32, EVENT::Register>),
33        /// Concatenated sequences have been played the amount of times defined in LOOP.CNT
34        (0x11C => events_loopsdone: ReadWrite<u32, EVENT::Register>),
35        (0x120 => _reserved2),
36        /// Shortcut register
37        (0x200 => shorts: ReadWrite<u32, SHORTS::Register>),
38        (0x204 => _reserved3),
39        /// Enable or disable interrupt
40        (0x300 => inten: ReadWrite<u32, INTEN::Register>),
41        /// Enable interrupt
42        (0x304 => intenset: ReadWrite<u32, INTEN::Register>),
43        /// Disable interrupt
44        (0x308 => intenclr: ReadWrite<u32, INTEN::Register>),
45        (0x30C => _reserved4),
46        /// PWM module enable register
47        (0x500 => enable: ReadWrite<u32, ENABLE::Register>),
48        /// Selects operating mode of the wave counter
49        (0x504 => mode: ReadWrite<u32, MODE::Register>),
50        /// Value up to which the pulse generator counter counts
51        (0x508 => countertop: ReadWrite<u32, COUNTERTOP::Register>),
52        /// Configuration for PWM_CLK
53        (0x50C => prescaler: ReadWrite<u32, PRESCALER::Register>),
54        /// Configuration of the decoder
55        (0x510 => decoder: ReadWrite<u32, DECODER::Register>),
56        /// Amount of playback of a loop
57        (0x514 => loopreg: ReadWrite<u32, LOOP::Register>),
58        (0x518 => _reserved5),
59        (0x520 => seq0: PwmSeqRegisters),
60        (0x530 => _reserved6),
61        (0x540 => seq1: PwmSeqRegisters),
62        (0x550 => _reserved7),
63        (0x560 => psel_out: [ReadWrite<u32>; 4]),
64        (0x570 => @END),
65    }
66}
67
68register_structs! {
69    PwmSeqRegisters {
70        (0x0 => seq_ptr: ReadWrite<u32>),
71        (0x4 => seq_cnt: ReadWrite<u32, SEQ_CNT::Register>),
72        (0x8 => seq_refresh: ReadWrite<u32, SEQ_REFRESH::Register>),
73        (0xC => seq_enddelay: ReadWrite<u32, SEQ_ENDDELAY::Register>),
74        (0x10 => @END),
75    }
76}
77
78register_bitfields![u32,
79    SHORTS [
80        /// Shortcut between EVENTS_SEQEND[0] event and TASKS_STOP task
81        SEQEND0_STOP 0,
82        /// Shortcut between EVENTS_SEQEND[1] event and TASKS_STOP task
83        SEQEND1_STOP 1,
84        /// Shortcut between EVENTS_LOOPSDONE event and TASKS_SEQSTART[0] task
85        LOOPSDONE_SEQSTART0 2,
86        /// Shortcut between EVENTS_LOOPSDONE event and TASKS_SEQSTART[1] task
87        LOOPSDONE_SEQSTART1 3,
88        /// Shortcut between EVENTS_LOOPSDONE event and TASKS_STOP task
89        LOOPSDONE_STOP 4
90    ],
91    INTEN [
92        /// Enable or disable interrupt on EVENTS_STOPPED event
93        STOPPED 1,
94        /// Enable or disable interrupt on EVENTS_SEQSTARTED[0] event
95        SEQSTARTED0 2,
96        /// Enable or disable interrupt on EVENTS_SEQSTARTED[1] event
97        SEQSTARTED1 3,
98        /// Enable or disable interrupt on EVENTS_SEQEND[0] event
99        SEQEND0 4,
100        /// Enable or disable interrupt on EVENTS_SEQEND[1] event
101        SEQEND1 5,
102        /// Enable or disable interrupt on EVENTS_PWMPERIODEND event
103        PWMPERIODEND 6,
104        /// Enable or disable interrupt on EVENTS_LOOPSDONE event
105        LOOPSDONE 7
106    ],
107    ENABLE [
108        ENABLE 0
109    ],
110    MODE [
111        UPDOWN OFFSET(0) NUMBITS(1) [
112            Up = 0,
113            UpAndDown = 1
114        ]
115    ],
116    COUNTERTOP [
117        COUNTERTOP OFFSET(0) NUMBITS(15) []
118    ],
119    PRESCALER [
120        PRESCALER OFFSET(0) NUMBITS(3) [
121            DIV_1 = 0,
122            DIV_2 = 1,
123            DIV_4 = 2,
124            DIV_8 = 3,
125            DIV_16 = 4,
126            DIV_32 = 5,
127            DIV_64 = 6,
128            DIV_128 = 7
129        ]
130    ],
131    DECODER [
132        /// How a sequence is read from RAM and spread to the compare register
133        LOAD OFFSET(0) NUMBITS(2) [
134            /// 1st half word (16-bit) used in all PWM channels 0..3
135            Common = 0,
136            /// 1st half word (16-bit) used in channel 0..1; 2nd word in channel 2..3
137            Grouped = 1,
138            /// 1st half word (16-bit) in ch.0; 2nd in ch.1; ...; 4th in ch.3
139            Individual = 2,
140            /// 1st half word (16-bit) in ch.0; 2nd in ch.1; ...; 4th in COUNTERTOP
141            Waveform = 3
142        ],
143        /// Selects source for advancing the active sequence
144        MODE OFFSET(8) NUMBITS(1) [
145            /// SEQ[n].REFRESH is used to determine loading internal compare registers
146            RefreshCount = 0,
147            /// NEXTSTEP task causes a new value to be loaded to internal compare registers
148            NextStep = 1
149        ]
150    ],
151    LOOP [
152        /// Number of playbacks of pattern cycles. 0 to disable.
153        CNT OFFSET(0) NUMBITS(16) []
154    ],
155    EVENT [
156        EVENT 0
157    ],
158    TASK [
159        TASK 0
160    ],
161    SEQ_CNT [
162        CNT OFFSET(0) NUMBITS(15) []
163    ],
164    SEQ_REFRESH [
165        CNT OFFSET(0) NUMBITS(24) []
166    ],
167    SEQ_ENDDELAY [
168        CNT OFFSET(0) NUMBITS(24) []
169    ]
170];
171
172/// `DUTY_CYCLES` is a static array that must be passed to the PWM hardware.
173///
174/// The nRF52 hardware uses this static array in memory to enable switching
175/// between multiple duty cycles automatically while generating the PWM output.
176/// This isn't ideal from a Rust perspective, but the peripheral hardware must
177/// be passed a pointer.
178static mut DUTY_CYCLES: [u16; 4] = [0; 4];
179
180pub struct Pwm {
181    registers: StaticRef<PwmRegisters>,
182}
183
184impl Pwm {
185    pub const fn new(registers: StaticRef<PwmRegisters>) -> Pwm {
186        Pwm { registers }
187    }
188
189    fn start_pwm(
190        &self,
191        pin: &nrf5x::pinmux::Pinmux,
192        frequency_hz: usize,
193        duty_cycle: usize,
194    ) -> Result<(), ErrorCode> {
195        // If frequency is 0, we can just stop the PWM and have it do nothing.
196        if frequency_hz == 0 {
197            return self.stop_pwm(pin);
198        }
199
200        let prescaler = 0;
201        let counter_top = (16000000 / frequency_hz) >> prescaler;
202
203        // Use the passed in duty cycle to calculate the value we pass to the
204        // hardware. A 50% duty cycle is half of counter_top, a 10% duty cycle
205        // would be 90% of counter_top.
206        //
207        //                               duty_cycle
208        //  dc_out = counter_top * (1 -  ---------- )
209        //                                5333333
210        let dc_out = counter_top - ((3 * duty_cycle) / frequency_hz);
211
212        // Configure the pin
213        self.registers.psel_out[0].set((*pin).into());
214
215        // Start by enabling the peripheral.
216        self.registers.enable.write(ENABLE::ENABLE::SET);
217        // Want count up mode.
218        self.registers.mode.write(MODE::UPDOWN::Up);
219        // Disable loop (repeat) mode.
220        self.registers.loopreg.write(LOOP::CNT.val(0));
221        // Set the decoder settings.
222        self.registers
223            .decoder
224            .write(DECODER::LOAD::Common + DECODER::MODE::RefreshCount);
225        // Set the prescaler.
226        self.registers.prescaler.write(PRESCALER::PRESCALER::DIV_1);
227        // Set the value to count to.
228        self.registers
229            .countertop
230            .write(COUNTERTOP::COUNTERTOP.val(counter_top as u32));
231
232        // Setup the duty cycles
233        unsafe {
234            DUTY_CYCLES[0] = dc_out as u16;
235        }
236        let duty_cycles: *const [u16; 4] = core::ptr::addr_of!(DUTY_CYCLES);
237        let duty_cycles: *const u16 = duty_cycles.cast();
238        self.registers.seq0.seq_ptr.set(duty_cycles as u32);
239        self.registers.seq0.seq_cnt.write(SEQ_CNT::CNT.val(1));
240        self.registers
241            .seq0
242            .seq_refresh
243            .write(SEQ_REFRESH::CNT.val(0));
244        self.registers
245            .seq0
246            .seq_enddelay
247            .write(SEQ_ENDDELAY::CNT.val(0));
248
249        // Start
250        self.registers.tasks_seqstart[0].write(TASK::TASK::SET);
251
252        Ok(())
253    }
254
255    fn stop_pwm(&self, _pin: &nrf5x::pinmux::Pinmux) -> Result<(), ErrorCode> {
256        self.registers.tasks_stop.write(TASK::TASK::SET);
257        self.registers.enable.write(ENABLE::ENABLE::CLEAR);
258        Ok(())
259    }
260}
261
262impl hil::pwm::Pwm for Pwm {
263    type Pin = nrf5x::pinmux::Pinmux;
264
265    fn start(&self, pin: &Self::Pin, frequency: usize, duty_cycle: usize) -> Result<(), ErrorCode> {
266        self.start_pwm(pin, frequency, duty_cycle)
267    }
268
269    fn stop(&self, pin: &Self::Pin) -> Result<(), ErrorCode> {
270        self.stop_pwm(pin)
271    }
272
273    fn get_maximum_frequency_hz(&self) -> usize {
274        // Counter runs at 16 MHz, and the minimum value for the COUNTERTOP
275        // register is 3. 16000000 / 3 = 5333333
276        5333333
277    }
278
279    fn get_maximum_duty_cycle(&self) -> usize {
280        // We use the max frequency as the max duty cycle as well. This makes
281        // calculating `dc_out` straightforward.
282        5333333
283    }
284}