rp2350 0.1.0

Hardware Abstraction Layer for RP2350 microcontrollers
Documentation
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! WATCHDOG HAL for RP2350
//!
//! This module provides access to the watchdog timer for system reset
//! and scratch registers for data persistence through resets.
//!
//! ## Features
//!
//! - Configurable watchdog timeout (up to ~8.3 seconds at 1µs tick)
//! - Pause during debug
//! - Software reset trigger
//! - 8 scratch registers for data persistence
//! - Reset reason detection
//! - Full system reboot support
//!
//! ## Example
//!
//! ```ignore
//! use rp2350::watchdog::Watchdog;
//! use rp2350::Peripherals;
//!
//! let dp = Peripherals::take().unwrap();
//! let wd = Watchdog::init(dp.WATCHDOG);
//!
//! // Check reset reason
//! let reason = wd.reset_reason();
//!
//! // Configure for 1 second timeout
//! wd.start(1_000_000);
//!
//! // In main loop, feed the watchdog
//! loop {
//!     // Do work...
//!     wd.feed();
//! }
//! ```
//!
//! ## Full System Reboot
//!
//! ```ignore
//! use rp2350::watchdog::Watchdog;
//! use rp2350::Peripherals;
//!
//! let dp = Peripherals::take().unwrap();
//! let wd = Watchdog::init(dp.WATCHDOG);
//!
//! // Reboot into regular flash path after 100ms
//! wd.reboot(100);
//! ```

use core::cell::Cell;

use crate::Steal;
use pastey::paste;
use rp2350_pac::PSM;
use rp2350_pac::psm::Wdsel;

/// Magic value indicating a non-reboot watchdog reset
const WATCHDOG_NON_REBOOT_MAGIC: u32 = 0x6ab73121;

/// Magic value for reboot with specific PC/SP
const WATCHDOG_REBOOT_MAGIC: u32 = 0xb007c0d3;

/// All PSM blocks to reset on watchdog (everything except ROSC and XOSC)
///
/// This mask includes all power state machine blocks that should be reset
/// during a full system reboot. ROSC and XOSC are excluded to maintain
/// clock stability during the reset process.
const PSM_WDSEL_RESET_BITS: u32 = Wdsel::PROC1
    | Wdsel::PROC0
    | Wdsel::ACCESSCTRL
    | Wdsel::SIO
    | Wdsel::XIP
    | Wdsel::SRAM9
    | Wdsel::SRAM8
    | Wdsel::SRAM7
    | Wdsel::SRAM6
    | Wdsel::SRAM5
    | Wdsel::SRAM4
    | Wdsel::SRAM3
    | Wdsel::SRAM2
    | Wdsel::SRAM1
    | Wdsel::SRAM0
    | Wdsel::BOOTRAM
    | Wdsel::ROM
    | Wdsel::BUSFABRIC
    | Wdsel::PSM_READY
    | Wdsel::CLOCKS
    | Wdsel::RESETS
    | Wdsel::OTP
    | Wdsel::PROC_COLD;
// Excluded: ROSC and XOSC to maintain clock stability

/// Maximum watchdog load value (24-bit counter)
const WATCHDOG_LOAD_MAX: u32 = 0x00ffffff;

/// Reset reason
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum ResetReason {
    /// Hardware reset or power-on
    PowerOn,
    /// Watchdog timer expired
    WatchdogTimeout,
    /// Watchdog force triggered
    WatchdogForce,
    /// Unknown/multiple reasons
    Unknown(u32),
}

/// WATCHDOG peripheral wrapper
///
/// Provides access to watchdog timer and scratch registers.
/// Owns the PAC WATCHDOG peripheral to enforce proper ownership semantics.
pub struct Watchdog {
    watchdog: rp2350_pac::WATCHDOG,
    /// Last timeout written via [`Watchdog::start`] or [`Watchdog::feed_with`].
    load_value: Cell<u32>,
}

impl Watchdog {
    /// Initialize the Watchdog driver.
    ///
    /// # Arguments
    /// * `watchdog` - The WATCHDOG peripheral from PAC
    #[inline]
    pub fn init(watchdog: rp2350_pac::WATCHDOG) -> Self {
        Self {
            watchdog,
            load_value: Cell::new(0),
        }
    }

    /// Obtain a Watchdog handle without ownership checks.
    ///
    /// # Safety
    ///
    /// The caller must ensure the peripheral has been initialised
    /// and that no data races occur.
    #[inline]
    pub unsafe fn steal() -> Steal<Self> {
        Steal(Self::init(unsafe { rp2350_pac::WATCHDOG::steal() }))
    }

    /// Get reference to the underlying register block
    ///
    /// # Safety
    /// Direct register access can bypass the HAL's safety guarantees.
    /// The caller must ensure operations do not conflict with the HAL state.
    #[inline]
    pub unsafe fn regs(&self) -> &rp2350_pac::watchdog::RegisterBlock {
        &self.watchdog
    }

    /// Release the WATCHDOG peripheral
    #[inline]
    pub fn release(self) -> rp2350_pac::WATCHDOG {
        self.watchdog
    }

    // ========================================================================
    // Watchdog Control
    // ========================================================================

    /// Start the watchdog with the specified timeout in microseconds.
    ///
    /// The watchdog resets the system if not fed within the timeout period.
    /// The timeout is clamped to the 24-bit maximum (`0xFFFFFF` µs ≈ 16.7 s).
    ///
    /// # Arguments
    /// * `timeout_us` - Timeout in microseconds
    pub fn start(&self, timeout_us: u32) {
        self.load_value.set(timeout_us.min(WATCHDOG_LOAD_MAX));
        self.watchdog.load.write_load(self.load_value.get());
        self.watchdog.ctrl.set_enable();
    }

    /// Feed (reload) the watchdog to prevent reset.
    ///
    /// Reloads with the timeout value last set via [`Watchdog::start`] or
    /// [`Watchdog::feed_with`]. Call regularly within the timeout period.
    #[inline]
    pub fn feed(&self) {
        self.watchdog.load.write_load(self.load_value.get());
    }

    /// Feed the watchdog and set a new timeout value.
    #[inline]
    pub fn feed_with(&self, timeout_us: u32) {
        self.load_value.set(timeout_us.min(WATCHDOG_LOAD_MAX));
        self.watchdog.load.write_load(self.load_value.get());
    }

    /// Disable the watchdog
    #[inline]
    pub fn disable(&self) {
        self.watchdog.ctrl.clr_enable();
    }

    /// Check if the watchdog is enabled
    #[inline]
    pub fn is_enabled(&self) -> bool {
        self.watchdog.ctrl.enable()
    }

    /// Get the current countdown time in microseconds
    #[inline]
    pub fn time_remaining(&self) -> u32 {
        self.watchdog.ctrl.time()
    }

    /// Get the remaining time before watchdog reset in milliseconds
    #[inline]
    pub fn time_remaining_ms(&self) -> u32 {
        self.time_remaining() / 1000
    }

    /// Trigger an immediate watchdog reset
    #[inline]
    pub fn force_reset(&self) {
        self.watchdog.ctrl.trigger_trigger();
    }

    // ========================================================================
    // Debug Control
    // ========================================================================

    /// Pause watchdog when processor 0 is in debug mode
    #[inline]
    pub fn pause_on_debug0(&self, pause: bool) {
        if pause {
            self.watchdog.ctrl.set_pause_dbg0();
        } else {
            self.watchdog.ctrl.clr_pause_dbg0();
        }
    }

    /// Pause watchdog when processor 1 is in debug mode
    #[inline]
    pub fn pause_on_debug1(&self, pause: bool) {
        if pause {
            self.watchdog.ctrl.set_pause_dbg1();
        } else {
            self.watchdog.ctrl.clr_pause_dbg1();
        }
    }

    /// Pause watchdog when JTAG is accessing the bus fabric
    #[inline]
    pub fn pause_on_jtag(&self, pause: bool) {
        if pause {
            self.watchdog.ctrl.set_pause_jtag();
        } else {
            self.watchdog.ctrl.clr_pause_jtag();
        }
    }

    /// Enable all debug pausing (convenience method)
    pub fn enable_debug_pause(&self) {
        self.pause_on_debug0(true);
        self.pause_on_debug1(true);
        self.pause_on_jtag(true);
    }

    /// Disable all debug pausing (convenience method)
    pub fn disable_debug_pause(&self) {
        self.pause_on_debug0(false);
        self.pause_on_debug1(false);
        self.pause_on_jtag(false);
    }

    // ========================================================================
    // Reset Reason
    // ========================================================================

    /// Get the reason for the last reset
    pub fn reset_reason(&self) -> ResetReason {
        let reason = &self.watchdog.reason;

        if reason.timer() {
            ResetReason::WatchdogTimeout
        } else if reason.force() {
            ResetReason::WatchdogForce
        } else if reason.read_bits() == 0 {
            ResetReason::PowerOn
        } else {
            ResetReason::Unknown(reason.read_bits())
        }
    }

    /// Check if last reset was due to watchdog timeout
    #[inline]
    pub fn was_watchdog_reset(&self) -> bool {
        self.watchdog.reason.timer()
    }

    /// Check if last reset was due to watchdog force trigger
    #[inline]
    pub fn was_force_reset(&self) -> bool {
        self.watchdog.reason.force()
    }

    /// Check if the last reset was caused by the watchdog (any reason)
    #[inline]
    pub fn caused_reboot(&self) -> bool {
        self.watchdog.reason.read_bits() != 0
    }

    /// Check if the last reset was caused by `enable_watchdog()`
    ///
    /// Distinguishes between a reset from the regular watchdog timer
    /// versus a reboot initiated by `reboot()` or `reboot_to_address()`.
    #[inline]
    pub fn enable_caused_reboot(&self) -> bool {
        self.watchdog.reason.read_bits() != 0
            && self.watchdog.scratch4.read_bits() == WATCHDOG_NON_REBOOT_MAGIC
    }

    // ========================================================================
    // Scratch Registers
    // ========================================================================

    /// Read a scratch register (0-7)
    ///
    /// Scratch registers persist through soft resets.
    pub fn read_scratch(&self, index: usize) -> u32 {
        assert!(index < 8, "scratch index must be 0-7");
        match index {
            0 => self.watchdog.scratch0.read_bits(),
            1 => self.watchdog.scratch1.read_bits(),
            2 => self.watchdog.scratch2.read_bits(),
            3 => self.watchdog.scratch3.read_bits(),
            4 => self.watchdog.scratch4.read_bits(),
            5 => self.watchdog.scratch5.read_bits(),
            6 => self.watchdog.scratch6.read_bits(),
            7 => self.watchdog.scratch7.read_bits(),
            _ => unreachable!(),
        }
    }

    /// Write a scratch register (0-7)
    ///
    /// Scratch registers persist through soft resets.
    pub fn write_scratch(&self, index: usize, value: u32) {
        assert!(index < 8, "scratch index must be 0-7");
        match index {
            0 => self.watchdog.scratch0.write_bits(value),
            1 => self.watchdog.scratch1.write_bits(value),
            2 => self.watchdog.scratch2.write_bits(value),
            3 => self.watchdog.scratch3.write_bits(value),
            4 => self.watchdog.scratch4.write_bits(value),
            5 => self.watchdog.scratch5.write_bits(value),
            6 => self.watchdog.scratch6.write_bits(value),
            7 => self.watchdog.scratch7.write_bits(value),
            _ => unreachable!(),
        }
    }

    // Per-register accessors (`scratch0`..`scratch7`, `set_scratch0`..`set_scratch7`)
    // are generated by `impl_scratch!` below.

    // ========================================================================
    // Watchdog-based Enable/Reboot
    // ========================================================================

    /// Enable watchdog with the specified timeout
    ///
    /// This enables the watchdog as a regular watchdog timer (not for reboot).
    /// The `feed()` function must be called periodically to prevent reset.
    ///
    /// # Arguments
    /// * `delay_ms` - Timeout in milliseconds (max ~8300ms)
    /// * `pause_on_debug` - Whether to pause the watchdog during debug
    pub fn enable_watchdog(&self, delay_ms: u32, pause_on_debug: bool) {
        self.watchdog.scratch4.write_bits(WATCHDOG_NON_REBOOT_MAGIC);

        self.configure_watchdog_reset(delay_ms, pause_on_debug);
    }

    /// Perform a full system reboot
    ///
    /// This function initiates a complete system reset using the watchdog timer.
    /// After the specified delay, the system will reset and boot from flash.
    ///
    /// # Arguments
    /// * `delay_ms` - Delay in milliseconds before reset (0 = immediate)
    ///
    /// # Note
    /// This function does not return. The system will reset after the delay.
    pub fn reboot(&self, delay_ms: u32) -> ! {
        self.watchdog.scratch4.write_bits(0);
        self.configure_watchdog_reset(delay_ms, false);

        loop {
            rp2350_rt::asm::wfi();
        }
    }

    /// Perform a full system reboot to a specific address
    ///
    /// This function initiates a complete system reset and configures the
    /// Boot ROM to jump to a specific program counter (PC) and stack pointer (SP)
    /// after the reset.
    ///
    /// # Arguments
    /// * `pc` - Program counter (entry point) to jump to after reset
    /// * `sp` - Stack pointer value to set before jumping
    /// * `delay_ms` - Delay in milliseconds before reset (0 = immediate)
    ///
    /// # Safety
    ///
    /// `pc` must be a valid, aligned code address and `sp` must point to
    /// a valid stack region. Invalid values cause undefined behaviour
    /// after reset.
    pub unsafe fn reboot_to_address(&self, pc: u32, sp: u32, delay_ms: u32) -> ! {
        self.watchdog.ctrl.clr_enable();

        let pc_thumb = pc | 1;
        self.watchdog.scratch4.write_bits(WATCHDOG_REBOOT_MAGIC);
        self.watchdog
            .scratch5
            .write_bits(pc_thumb ^ (WATCHDOG_REBOOT_MAGIC.wrapping_neg()));
        self.watchdog.scratch6.write_bits(sp);
        self.watchdog.scratch7.write_bits(pc_thumb);

        self.configure_watchdog_reset(delay_ms, false);

        loop {
            rp2350_rt::asm::wfi();
        }
    }

    // ========================================================================
    // Internal Helpers
    // ========================================================================

    /// Configure watchdog for system reset (internal helper)
    fn configure_watchdog_reset(&self, delay_ms: u32, pause_on_debug: bool) {
        let psm = unsafe { PSM::steal() };

        self.watchdog.ctrl.clr_enable();
        psm.wdsel.set_bits(PSM_WDSEL_RESET_BITS);

        if pause_on_debug {
            self.watchdog.ctrl.set_pause_dbg0();
            self.watchdog.ctrl.set_pause_dbg1();
            self.watchdog.ctrl.set_pause_jtag();
        } else {
            self.watchdog.ctrl.clr_pause_dbg0();
            self.watchdog.ctrl.clr_pause_dbg1();
            self.watchdog.ctrl.clr_pause_jtag();
        }

        if delay_ms == 0 {
            self.watchdog.ctrl.trigger_trigger();
        } else {
            let load_value = (delay_ms.saturating_mul(1000)).min(WATCHDOG_LOAD_MAX);
            self.watchdog.load.write_load(load_value);
            self.watchdog.ctrl.set_enable();
        }
    }
}

macro_rules! impl_scratch {
    ($($n:literal),+ $(,)?) => {
        paste! {
            $(
                impl Watchdog {
                    #[doc = concat!("Read scratch register ", $n, ".")]
                    #[inline]
                    pub fn [<scratch $n>](&self) -> u32 {
                        self.watchdog.[<scratch $n>].read_bits()
                    }

                    #[doc = concat!("Write scratch register ", $n, ".")]
                    #[inline]
                    pub fn [<set_scratch $n>](&self, value: u32) {
                        self.watchdog.[<scratch $n>].write_bits(value);
                    }
                }
            )+
        }
    };
}

impl_scratch!(0, 1, 2, 3, 4, 5, 6, 7);

// ============================================================================
// Module-level Convenience Functions
// ============================================================================

/// Perform a full system reboot (module-level convenience function)
///
/// This function uses unsafe global access to the WATCHDOG peripheral.
/// Prefer using `Watchdog::reboot()` when you have an owned instance.
///
/// # Arguments
/// * `delay_ms` - Delay in milliseconds before reset (0 = immediate)
///
/// # Note
/// This function does not return. The system will reset after the delay.
///
/// # Example
///
/// ```ignore
/// use rp2350::watchdog;
///
/// // Reboot after 10ms
/// watchdog::reboot(10);
/// ```
pub fn reboot(delay_ms: u32) -> ! {
    unsafe { Watchdog::steal() }.reboot(delay_ms)
}

/// Perform a full system reboot to a specific address (module-level convenience)
///
/// # Arguments
/// * `pc` - Program counter (entry point) to jump to after reset
/// * `sp` - Stack pointer value to set before jumping
/// * `delay_ms` - Delay in milliseconds before reset (0 = immediate)
///
/// # Safety
///
/// `pc` must be a valid, aligned code address and `sp` must point to
/// a valid stack region. Invalid values cause undefined behaviour
/// after reset.
pub unsafe fn reboot_to_address(pc: u32, sp: u32, delay_ms: u32) -> ! {
    unsafe { Watchdog::steal().reboot_to_address(pc, sp, delay_ms) }
}

/// Check if the last reset was caused by the watchdog (module-level convenience)
#[inline]
pub fn caused_reboot() -> bool {
    unsafe { Watchdog::steal() }.caused_reboot()
}

/// Check if the last reset was caused by `enable_watchdog()` (module-level convenience)
#[inline]
pub fn enable_caused_reboot() -> bool {
    unsafe { Watchdog::steal() }.enable_caused_reboot()
}