From fd1e822e19294b709124b7be75477b7e0bd0963a Mon Sep 17 00:00:00 2001 From: Vincent Bonduro Date: Sat, 31 Oct 2026 05:56:38 -0400 Subject: [PATCH] pico2w: add bsp module for pin assignments and peripheral groups Board::init() configures the clock profile and takes the HAL peripherals, returning them grouped per subsystem (SD, display, buttons, audio, WiFi). Drivers take their group by value, so each peripheral is claimed once and the compiler enforces it. - Move ClockProfile, Irqs/WifiIrqs and WifiPeriphs out of main.rs. - HwDisplay::new borrows DisplayPeriphs via Peri::reborrow, so GameDisplay::new_after_splash no longer needs unsafe steal(). - InputHandler::new takes ButtonPeriphs; init_sd_card takes SdPeriphs. - Add audio::init_i2s for the PIO0 I2S setup previously inline in main. Co-Authored-By: Claude Sonnet 5.5 --- platform/pico2w/src/audio.rs | 28 ++++ platform/pico2w/src/bsp.rs | 264 ++++++++++++++++++++++++++++++ platform/pico2w/src/display/hw.rs | 66 ++++---- platform/pico2w/src/input.rs | 33 ++-- platform/pico2w/src/lib.rs | 3 + platform/pico2w/src/main.rs | 217 +++--------------------- 6 files changed, 364 insertions(+), 247 deletions(-) create mode 100644 platform/pico2w/src/bsp.rs diff --git a/platform/pico2w/src/audio.rs b/platform/pico2w/src/audio.rs index 144425c..c0f0c8b 100644 --- a/platform/pico2w/src/audio.rs +++ b/platform/pico2w/src/audio.rs @@ -95,3 +95,31 @@ fn samples_i16_to_i2s(samples: &[i16], buf: &mut [u32]) -> usize { } pairs } + +/// Bring up the I2S output on PIO0 and start it. +pub fn init_i2s( + periphs: crate::bsp::AudioPeriphs, + irqs: crate::bsp::Irqs, +) -> embassy_rp::pio_programs::i2s::PioI2sOut<'static, embassy_rp::peripherals::PIO0, 0> { + use embassy_rp::pio::Pio; + use embassy_rp::pio_programs::i2s::{PioI2sOut, PioI2sOutProgram}; + + let Pio { + mut common, sm0, .. + } = Pio::new(periphs.pio, irqs); + let prog = PioI2sOutProgram::new(&mut common); + let mut i2s = PioI2sOut::new( + &mut common, + sm0, + periphs.dma, + irqs, + periphs.data, + periphs.bclk, + periphs.lrclk, + SAMPLE_RATE, + 16, + &prog, + ); + i2s.start(); + i2s +} diff --git a/platform/pico2w/src/bsp.rs b/platform/pico2w/src/bsp.rs new file mode 100644 index 0000000..078bc20 --- /dev/null +++ b/platform/pico2w/src/bsp.rs @@ -0,0 +1,264 @@ +//! Board support: clock profile, interrupt bindings and the pin/peripheral +//! assignment for the Pico 2W + ILI9341 + SD + MAX98357A wiring. +//! +//! [`Board::init`] brings up the HAL once and returns every peripheral grouped +//! by the subsystem that uses it. Callers move a group out of the `Board` and +//! hand it to the driver, so "each peripheral is claimed once" is enforced by +//! the compiler rather than by `steal()` and a comment. +//! +//! Pin numbers live ONLY in this file; the full wiring table is in +//! `docs/wiring.md`. + +use embassy_rp::clocks::{ClockConfig, CoreVoltage}; +use embassy_rp::peripherals::{ + CORE1, DMA_CH0, DMA_CH1, DMA_CH2, DMA_CH3, FLASH, PIN_0, PIN_1, PIN_10, PIN_11, PIN_12, + PIN_13, PIN_14, PIN_15, PIN_16, PIN_17, PIN_2, PIN_20, PIN_21, PIN_22, PIN_23, PIN_24, PIN_25, + PIN_26, PIN_27, PIN_29, PIN_3, PIN_4, PIN_5, PIN_6, PIN_7, PIN_8, PIN_9, PIO0, PIO1, SPI0, + SPI1, WATCHDOG, +}; +use embassy_rp::pio::InterruptHandler as PioIrqHandler; +use embassy_rp::{bind_interrupts, dma, Peri}; + +// --------------------------------------------------------------------------- +// Clock profile +// --------------------------------------------------------------------------- + +/// A clock operating point: frequency and the core voltage it was validated at. +/// +/// Frequency and voltage are two halves of ONE decision, so they live in one +/// place. They were previously two independent `#[cfg]` cascades keyed on +/// overlapping-but-different feature sets, which had already drifted: `oc-266` +/// selected 266 MHz but fell through to V1_30, silently *not* reproducing the +/// "266 MHz @ V1_25" operating point it is named for. +struct ClockProfile { + hz: u32, + voltage: CoreVoltage, +} + +/// Stock overclock. NOT free of the SP-drift fault — see `OC_288`. +const OC_300: ClockProfile = ClockProfile { + hz: 300_000_000, + voltage: CoreVoltage::V1_30, +}; + +/// 288 MHz = PLL FBDIV 120 (VCO 1440) / POSTDIV 5 — one grid step below 300 on +/// the stock PLL config, and the fastest clock measured free of the SP-drift +/// fault. A frequency sweep by live PLL reprogramming put the failure cliff +/// between 288 and 300: at 300 the drift instrument logged 67.5 events per 1000 +/// work-ticks, while 288/276/264/252/240 logged zero across 13,567 ticks. A 24 h +/// soak at 288 on the real firmware logged 0 crashes. +/// +/// NOT proven safe: the cliff is bracketed only to (288, 300], so 288 may have +/// as little as 0.3% margin, untested against temperature and part-to-part +/// spread. `OC_266` is the more conservative shipping point. +/// See docs/investigations/sp-drift-root-cause.md. +const OC_288: ClockProfile = ClockProfile { + hz: 288_000_000, + voltage: CoreVoltage::V1_30, +}; + +const OC_280: ClockProfile = ClockProfile { + hz: 280_000_000, + voltage: CoreVoltage::V1_25, +}; + +/// 9 h clean on record at V1_25 — the voltage is part of that result. +const OC_266: ClockProfile = ClockProfile { + hz: 266_000_000, + voltage: CoreVoltage::V1_25, +}; + +/// Exactly one profile, chosen in priority order. Adding a profile is one const +/// plus one arm; frequency and voltage cannot desync. +const CLOCK: ClockProfile = if cfg!(feature = "oc-300") { + OC_300 +} else if cfg!(feature = "oc-288") { + OC_288 +} else if cfg!(feature = "oc-280") { + OC_280 +} else if cfg!(feature = "oc-266") { + OC_266 +} else { + OC_300 +}; + +// --------------------------------------------------------------------------- +// Interrupt bindings +// --------------------------------------------------------------------------- + +bind_interrupts!(pub struct Irqs { + PIO0_IRQ_0 => PioIrqHandler; + // CH0 and CH1 are always needed (audio DMA, display DMA). + // CH2 and CH3 are reserved for the WiFi CYW43439 PIO SPI driver; binding + // them unconditionally is safe — the handlers are no-ops when unused. + DMA_IRQ_0 => dma::InterruptHandler, + dma::InterruptHandler, + dma::InterruptHandler, + dma::InterruptHandler; +}); + +// WiFi uses PIO1: bound separately from `Irqs`. +bind_interrupts!(pub struct WifiIrqs { + PIO1_IRQ_0 => PioIrqHandler; +}); + +// --------------------------------------------------------------------------- +// Peripheral groups +// --------------------------------------------------------------------------- + +/// SD card on SPI0, plus its mode-select pin. +pub struct SdPeriphs { + pub spi: Peri<'static, SPI0>, + pub miso: Peri<'static, PIN_4>, + pub cs: Peri<'static, PIN_5>, + pub clk: Peri<'static, PIN_6>, + pub mosi: Peri<'static, PIN_7>, + /// GP17: selects SPI mode on the card module. Must stay driven for the + /// lifetime of the card. + pub mode: Peri<'static, PIN_17>, +} + +/// ILI9341 on SPI1. Used first by the blocking splash driver, then by the +/// async game driver (which also uses `dma`). +pub struct DisplayPeriphs { + pub spi: Peri<'static, SPI1>, + pub dc: Peri<'static, PIN_8>, + pub cs: Peri<'static, PIN_9>, + pub clk: Peri<'static, PIN_10>, + pub mosi: Peri<'static, PIN_11>, + pub rst: Peri<'static, PIN_12>, + pub backlight: Peri<'static, PIN_13>, + pub dma: Peri<'static, DMA_CH1>, +} + +/// The eight active-low Game Boy buttons. +pub struct ButtonPeriphs { + pub up: Peri<'static, PIN_21>, + pub down: Peri<'static, PIN_22>, + pub left: Peri<'static, PIN_26>, + pub right: Peri<'static, PIN_27>, + pub a: Peri<'static, PIN_0>, + pub b: Peri<'static, PIN_1>, + pub start: Peri<'static, PIN_2>, + pub select: Peri<'static, PIN_3>, +} + +/// MAX98357A I2S amplifier, driven by a PIO0 state machine. +pub struct AudioPeriphs { + pub pio: Peri<'static, PIO0>, + pub dma: Peri<'static, DMA_CH0>, + /// GP16: I2S data out. + pub data: Peri<'static, PIN_16>, + /// GP14: bit clock. + pub bclk: Peri<'static, PIN_14>, + /// GP15: left/right (word select) clock. + pub lrclk: Peri<'static, PIN_15>, +} + +/// All CYW43439 peripheral tokens, bundled for clean transfer from `main` into +/// the app state and ultimately into `WifiPortalScreen::start_portal`. +pub struct WifiPeriphs { + pub pwr: Peri<'static, PIN_23>, + pub dio: Peri<'static, PIN_24>, + pub cs: Peri<'static, PIN_25>, + pub clk: Peri<'static, PIN_29>, + pub pio1: Peri<'static, PIO1>, + pub dma_ch2: Peri<'static, DMA_CH2>, + pub dma_ch3: Peri<'static, DMA_CH3>, + /// PIO1 interrupt binding (from `WifiIrqs`). + pub pio_irqs: WifiIrqs, + /// DMA CH2/CH3 interrupt binding (from `Irqs`, which binds all DMA_IRQ_0 channels). + pub dma_irqs: Irqs, +} + +// --------------------------------------------------------------------------- +// Board +// --------------------------------------------------------------------------- + +/// Every peripheral the firmware uses, grouped by subsystem. +/// +/// Destructure by moving fields out; using a group twice is a compile error. +pub struct Board { + pub flash: Peri<'static, FLASH>, + pub watchdog: Peri<'static, WATCHDOG>, + pub core1: Peri<'static, CORE1>, + pub sd: SdPeriphs, + /// GP20: gates the SD module's VCC (HIGH = powered, LOW = off). Separate + /// from `sd` because boot sequencing toggles it around display init, + /// before the card driver exists. + pub sd_power: Peri<'static, PIN_20>, + pub display: DisplayPeriphs, + pub buttons: ButtonPeriphs, + pub audio: AudioPeriphs, + pub wifi: WifiPeriphs, +} + +impl Board { + /// System clock the selected profile runs the chip at, in Hz. + pub const fn sys_hz() -> u32 { + CLOCK.hz + } + + /// Configure clocks and core voltage from the selected profile and take + /// the HAL peripherals. Call once, after the core-0 memory guards and the + /// heap are set up. + pub fn init() -> Self { + let mut clk = + ClockConfig::system_freq(CLOCK.hz).expect("valid PLL params for target clock"); + clk.core_voltage = CLOCK.voltage; + let p = embassy_rp::init(embassy_rp::config::Config::new(clk)); + + Self { + flash: p.FLASH, + watchdog: p.WATCHDOG, + core1: p.CORE1, + sd: SdPeriphs { + spi: p.SPI0, + miso: p.PIN_4, + cs: p.PIN_5, + clk: p.PIN_6, + mosi: p.PIN_7, + mode: p.PIN_17, + }, + sd_power: p.PIN_20, + display: DisplayPeriphs { + spi: p.SPI1, + dc: p.PIN_8, + cs: p.PIN_9, + clk: p.PIN_10, + mosi: p.PIN_11, + rst: p.PIN_12, + backlight: p.PIN_13, + dma: p.DMA_CH1, + }, + buttons: ButtonPeriphs { + up: p.PIN_21, + down: p.PIN_22, + left: p.PIN_26, + right: p.PIN_27, + a: p.PIN_0, + b: p.PIN_1, + start: p.PIN_2, + select: p.PIN_3, + }, + audio: AudioPeriphs { + pio: p.PIO0, + dma: p.DMA_CH0, + data: p.PIN_16, + bclk: p.PIN_14, + lrclk: p.PIN_15, + }, + wifi: WifiPeriphs { + pwr: p.PIN_23, + dio: p.PIN_24, + cs: p.PIN_25, + clk: p.PIN_29, + pio1: p.PIO1, + dma_ch2: p.DMA_CH2, + dma_ch3: p.DMA_CH3, + pio_irqs: WifiIrqs, + dma_irqs: Irqs, + }, + } + } +} diff --git a/platform/pico2w/src/display/hw.rs b/platform/pico2w/src/display/hw.rs index 5f1f8c9..bfb4aee 100644 --- a/platform/pico2w/src/display/hw.rs +++ b/platform/pico2w/src/display/hw.rs @@ -6,9 +6,8 @@ use defmt::{info, warn}; use embassy_rp::gpio::{Level, Output}; -use embassy_rp::peripherals::{DMA_CH1, PIN_10, PIN_11, PIN_12, PIN_13, PIN_8, PIN_9, SPI1}; +use embassy_rp::peripherals::{DMA_CH1, SPI1}; use embassy_rp::spi::{Async, Blocking, Config as SpiConfig, Spi}; -use embassy_rp::Peri; use embassy_rp::{dma, interrupt}; use display_interface_spi::SPIInterface; @@ -24,6 +23,7 @@ use super::{ render_menu_row, scale_native_to_rgb565_range, Display, LoadingFrame, LoadingProgress, NativeFrame, RenderWindow, ScaledFrame, SCALED_FRAME_PIXELS, }; +use crate::bsp::DisplayPeriphs; use crate::menu::MenuFrame; // --------------------------------------------------------------------------- @@ -72,24 +72,25 @@ pub struct HwDisplay<'d> { impl<'d> HwDisplay<'d> { /// Initialise the ILI9341 and return a ready-to-use display. /// + /// Borrows the pins and SPI1 from `periphs` rather than consuming them, so + /// once this driver is dropped the bundle is free to hand to + /// [`GameDisplay::new_after_splash`] with no `steal()`. + /// /// The backlight is enabled immediately after hardware init. - pub fn new( - spi1: Peri<'d, SPI1>, - clk: Peri<'d, PIN_10>, - mosi: Peri<'d, PIN_11>, - cs_pin: Peri<'d, PIN_9>, - dc_pin: Peri<'d, PIN_8>, - rst_pin: Peri<'d, PIN_12>, - bl_pin: Peri<'d, PIN_13>, - ) -> Self { + pub fn new(periphs: &'d mut DisplayPeriphs) -> Self { let mut cfg = SpiConfig::default(); cfg.frequency = DISPLAY_SPI_HZ; - let spi = Spi::new_blocking_txonly(spi1, clk, mosi, cfg); - let cs = Output::new(cs_pin, Level::High); - let dc = Output::new(dc_pin, Level::Low); - let rst = Output::new(rst_pin, Level::High); - let mut bl = Output::new(bl_pin, Level::Low); + let spi = Spi::new_blocking_txonly( + periphs.spi.reborrow(), + periphs.clk.reborrow(), + periphs.mosi.reborrow(), + cfg, + ); + let cs = Output::new(periphs.cs.reborrow(), Level::High); + let dc = Output::new(periphs.dc.reborrow(), Level::Low); + let rst = Output::new(periphs.rst.reborrow(), Level::High); + let mut bl = Output::new(periphs.backlight.reborrow(), Level::Low); let spi_dev = ExclusiveDevice::new(spi, cs, embassy_time::Delay); let di = SPIInterface::new(spi_dev, dc); @@ -176,18 +177,10 @@ pub struct GameDisplay<'d> { impl<'d> GameDisplay<'d> { /// Initialise async SPI for the game loop after `HwDisplay` has been dropped. /// - /// # Safety - /// `HwDisplay` must have been fully dropped before calling this so that SPI1 - /// and all display GPIO pins are free to be re-claimed. - pub unsafe fn new_after_splash( - clk: Peri<'d, PIN_10>, - mosi: Peri<'d, PIN_11>, - cs_pin: Peri<'d, PIN_9>, - dc_pin: Peri<'d, PIN_8>, - rst_pin: Peri<'d, PIN_12>, - bl_pin: Peri<'d, PIN_13>, - spi1: Peri<'d, SPI1>, - dma: Peri<'d, DMA_CH1>, + /// `HwDisplay` borrows `periphs`, so the borrow checker guarantees it is + /// gone before this can be called. + pub fn new_after_splash( + periphs: DisplayPeriphs, irqs: impl interrupt::typelevel::Binding< interrupt::typelevel::DMA_IRQ_0, dma::InterruptHandler, @@ -213,11 +206,18 @@ impl<'d> GameDisplay<'d> { let mut cfg = SpiConfig::default(); cfg.frequency = DISPLAY_SPI_HZ; - let spi = Spi::new_txonly(spi1, clk, mosi, dma, irqs, cfg); - let cs = Output::new(cs_pin, Level::High); - let dc = Output::new(dc_pin, Level::Low); - let rst = Output::new(rst_pin, Level::High); - let bl = Output::new(bl_pin, Level::High); + let spi = Spi::new_txonly( + periphs.spi, + periphs.clk, + periphs.mosi, + periphs.dma, + irqs, + cfg, + ); + let cs = Output::new(periphs.cs, Level::High); + let dc = Output::new(periphs.dc, Level::Low); + let rst = Output::new(periphs.rst, Level::High); + let bl = Output::new(periphs.backlight, Level::High); info!("display: async SPI re-initialised for game loop"); Self { diff --git a/platform/pico2w/src/input.rs b/platform/pico2w/src/input.rs index e016070..6f09ce9 100644 --- a/platform/pico2w/src/input.rs +++ b/platform/pico2w/src/input.rs @@ -4,14 +4,12 @@ //! All buttons are wired active-low (one side to GPIO, other to GND). Internal //! pull-ups are enabled so no external resistors are needed. //! -//! Pin assignments are an application-level concern; see `main.rs`. +//! Pin assignments are a board concern; see `bsp.rs`. #[cfg(target_arch = "arm")] use embassy_rp::gpio::{Input, Pull}; #[cfg(target_arch = "arm")] -use embassy_rp::peripherals::{PIN_0, PIN_1, PIN_2, PIN_21, PIN_22, PIN_26, PIN_27, PIN_3}; -#[cfg(target_arch = "arm")] -use embassy_rp::Peri; +use crate::bsp::ButtonPeriphs; #[cfg(target_arch = "arm")] use embassy_time::Instant; @@ -204,25 +202,16 @@ pub struct InputHandler<'d> { #[cfg(target_arch = "arm")] impl<'d> InputHandler<'d> { - pub fn new( - up_pin: Peri<'d, PIN_21>, - down_pin: Peri<'d, PIN_22>, - left_pin: Peri<'d, PIN_26>, - right_pin: Peri<'d, PIN_27>, - a_pin: Peri<'d, PIN_0>, - b_pin: Peri<'d, PIN_1>, - start_pin: Peri<'d, PIN_2>, - select_pin: Peri<'d, PIN_3>, - ) -> Self { + pub fn new(pins: ButtonPeriphs) -> Self { Self { - up: Input::new(up_pin, Pull::Up), - down: Input::new(down_pin, Pull::Up), - left: Input::new(left_pin, Pull::Up), - right: Input::new(right_pin, Pull::Up), - a: Input::new(a_pin, Pull::Up), - b: Input::new(b_pin, Pull::Up), - start: Input::new(start_pin, Pull::Up), - select: Input::new(select_pin, Pull::Up), + up: Input::new(pins.up, Pull::Up), + down: Input::new(pins.down, Pull::Up), + left: Input::new(pins.left, Pull::Up), + right: Input::new(pins.right, Pull::Up), + a: Input::new(pins.a, Pull::Up), + b: Input::new(pins.b, Pull::Up), + start: Input::new(pins.start, Pull::Up), + select: Input::new(pins.select, Pull::Up), state: InputState::default(), } } diff --git a/platform/pico2w/src/lib.rs b/platform/pico2w/src/lib.rs index c39ee2a..d872e2f 100644 --- a/platform/pico2w/src/lib.rs +++ b/platform/pico2w/src/lib.rs @@ -4,6 +4,9 @@ extern crate alloc; #[cfg(target_arch = "arm")] pub mod audio; +/// Pin assignments, clock profile and peripheral grouping. ARM-only. +#[cfg(target_arch = "arm")] +pub mod bsp; pub mod crash; pub mod display; #[cfg(target_arch = "arm")] diff --git a/platform/pico2w/src/main.rs b/platform/pico2w/src/main.rs index de378db..a25b879 100644 --- a/platform/pico2w/src/main.rs +++ b/platform/pico2w/src/main.rs @@ -25,17 +25,11 @@ static HEAP: Heap = Heap::empty(); use defmt::info; use embassy_executor::Spawner; use embassy_rp::gpio::{Level, Output}; -use embassy_rp::peripherals::{ - CORE1, DMA_CH0, DMA_CH1, DMA_CH2, DMA_CH3, PIN_10, PIN_11, PIN_12, PIN_13, PIN_17, PIN_4, - PIN_5, PIN_6, PIN_7, PIN_8, PIN_9, PIO0, SPI0, SPI1, -}; -use embassy_rp::peripherals::{PIN_23, PIN_24, PIN_25, PIN_29, PIO1}; -use embassy_rp::pio::{InterruptHandler as PioIrqHandler, Pio}; -use embassy_rp::pio_programs::i2s::{PioI2sOut, PioI2sOutProgram}; +use embassy_rp::peripherals::SPI0; use embassy_rp::spi::{self, Blocking, Spi}; +use embassy_rp::peripherals::CORE1; use embassy_rp::watchdog::Watchdog; use embassy_rp::Peri; -use embassy_rp::{bind_interrupts, dma}; use embassy_time::{Delay, Duration}; use embedded_hal_bus::spi::ExclusiveDevice; use embedded_sdmmc::SdCard; @@ -47,7 +41,8 @@ use defmt_rtt as _; use rustyboy_pico2w::crash; -use rustyboy_pico2w::audio::{AudioBuffers, SAMPLE_RATE}; +use rustyboy_pico2w::audio::{init_i2s, AudioBuffers}; +use rustyboy_pico2w::bsp::{Board, Irqs, SdPeriphs, WifiPeriphs}; use rustyboy_pico2w::display::hw::{GameDisplay, HwDisplay}; use rustyboy_pico2w::flash_rom::{new_onboard_flash, probe_staged_rom}; use rustyboy_pico2w::input::{ButtonState, InputHandler}; @@ -67,89 +62,9 @@ const WATCHDOG_WINDOW_MS: u64 = 16_000; const WATCHDOG_MAX_WINDOW_MS: u64 = (1 << 24) / 1_000; const _: () = assert!(WATCHDOG_WINDOW_MS <= WATCHDOG_MAX_WINDOW_MS); -/// A clock operating point: frequency and the core voltage it was validated at. -/// -/// Frequency and voltage are two halves of ONE decision, so they live in one -/// place. They were previously two independent `#[cfg]` cascades keyed on -/// overlapping-but-different feature sets, which had already drifted: `oc-266` -/// selected 266 MHz but fell through to V1_30, silently *not* reproducing the -/// "266 MHz @ V1_25" operating point it is named for. -struct ClockProfile { - hz: u32, - voltage: embassy_rp::clocks::CoreVoltage, -} - -use embassy_rp::clocks::CoreVoltage; - -/// Stock overclock. NOT free of the SP-drift fault — see `OC_288`. -const OC_300: ClockProfile = ClockProfile { - hz: 300_000_000, - voltage: CoreVoltage::V1_30, -}; - -/// 288 MHz = PLL FBDIV 120 (VCO 1440) / POSTDIV 5 — one grid step below 300 on -/// the stock PLL config, and the fastest clock measured free of the SP-drift -/// fault. A frequency sweep by live PLL reprogramming put the failure cliff -/// between 288 and 300: at 300 the drift instrument logged 67.5 events per 1000 -/// work-ticks, while 288/276/264/252/240 logged zero across 13,567 ticks. A 24 h -/// soak at 288 on the real firmware logged 0 crashes. -/// -/// NOT proven safe: the cliff is bracketed only to (288, 300], so 288 may have -/// as little as 0.3% margin, untested against temperature and part-to-part -/// spread. `OC_266` is the more conservative shipping point. -/// See docs/investigations/sp-drift-root-cause.md. -const OC_288: ClockProfile = ClockProfile { - hz: 288_000_000, - voltage: CoreVoltage::V1_30, -}; - -const OC_280: ClockProfile = ClockProfile { - hz: 280_000_000, - voltage: CoreVoltage::V1_25, -}; - -/// 9 h clean on record at V1_25 — the voltage is part of that result. -const OC_266: ClockProfile = ClockProfile { - hz: 266_000_000, - voltage: CoreVoltage::V1_25, -}; - -/// Exactly one profile, chosen in priority order. Adding a profile is one const -/// plus one arm; frequency and voltage cannot desync. -const CLOCK: ClockProfile = if cfg!(feature = "oc-300") { - OC_300 -} else if cfg!(feature = "oc-288") { - OC_288 -} else if cfg!(feature = "oc-280") { - OC_280 -} else if cfg!(feature = "oc-266") { - OC_266 -} else { - OC_300 -}; - -const TARGET_SYS_HZ: u32 = CLOCK.hz; -const TARGET_CORE_VOLTAGE: CoreVoltage = CLOCK.voltage; - const FIRMWARE_VERSION: &str = env!("CARGO_PKG_VERSION"); pub(crate) const CYCLES_PER_FRAME: u64 = 70_224; -bind_interrupts!(struct Irqs { - PIO0_IRQ_0 => PioIrqHandler; - // CH0 and CH1 are always needed (display DMA, audio DMA). - // CH2 and CH3 are reserved for the WiFi CYW43439 PIO SPI driver; binding - // them unconditionally is safe — the handlers are no-ops when unused. - DMA_IRQ_0 => dma::InterruptHandler, - dma::InterruptHandler, - dma::InterruptHandler, - dma::InterruptHandler; -}); - -// WiFi uses PIO1: bind it separately, scoped to the wifi feature. -bind_interrupts!(struct WifiIrqs { - PIO1_IRQ_0 => PioIrqHandler; -}); - #[unsafe(link_section = ".bi_entries")] #[used] pub static PICOTOOL_ENTRIES: [embassy_rp::binary_info::EntryAddr; 3] = [ @@ -183,28 +98,6 @@ pub(crate) fn poll_once(future: core::pin::Pin<&mut F>) -> bool { matches!(future.poll(&mut cx), Poll::Ready(_)) } -// --------------------------------------------------------------------------- -// WiFi peripheral tokens (consumed once when the portal starts) -// --------------------------------------------------------------------------- - -/// All CYW43439 peripheral tokens, bundled for clean transfer from `main` into -/// [`App`] and ultimately into `WifiPortalScreen::start_portal`. -/// -/// Wrapped in `Option` so they can be consumed (`take`) exactly once. -pub(crate) struct WifiPeriphs { - pub pwr: Peri<'static, PIN_23>, - pub dio: Peri<'static, PIN_24>, - pub cs: Peri<'static, PIN_25>, - pub clk: Peri<'static, PIN_29>, - pub pio1: Peri<'static, PIO1>, - pub dma_ch2: Peri<'static, DMA_CH2>, - pub dma_ch3: Peri<'static, DMA_CH3>, - /// PIO1 interrupt binding (from `WifiIrqs`). - pub pio_irqs: WifiIrqs, - /// DMA CH2/CH3 interrupt binding (from `Irqs`, which binds all DMA_IRQ_0 channels). - pub dma_irqs: Irqs, -} - // --------------------------------------------------------------------------- // App state machine // --------------------------------------------------------------------------- @@ -368,24 +261,17 @@ impl core::ops::DerefMut for SdBus { } /// Bring up the SD card on SPI0 and mount it. -fn init_sd_card( - mode_pin: Peri<'static, PIN_17>, - spi0: Peri<'static, SPI0>, - clk: Peri<'static, PIN_6>, - mosi: Peri<'static, PIN_7>, - miso: Peri<'static, PIN_4>, - cs_pin: Peri<'static, PIN_5>, -) -> SdBus { +fn init_sd_card(p: SdPeriphs) -> SdBus { // SD card — always initialised so the ROM list is available. // Drive the SD mode pin BEFORE any bus traffic. Nothing clocked SPI0 before // this commit (SdCard construction is lazy), so its position did not matter; // the power-up clocks below are the first transfer, and they must not be // sent while this pin is still in its reset state. - let sd_mode = Output::new(mode_pin, Level::High); + let sd_mode = Output::new(p.mode, Level::High); let mut spi_cfg = spi::Config::default(); spi_cfg.frequency = 400_000; - let mut spi_bus = Spi::new_blocking(spi0, clk, mosi, miso, spi_cfg); + let mut spi_bus = Spi::new_blocking(p.spi, p.clk, p.mosi, p.miso, spi_cfg); rp_pac::PADS_BANK0.gpio(4).modify(|w| w.set_pue(true)); // SD power-up clocks. The SD spec requires >=74 clock cycles at 400 kHz with @@ -394,7 +280,7 @@ fn init_sd_card( // some don't") — and this firmware previously went straight from // construction to CMD0. CS is therefore created FIRST, held high for the // clocks, then moved into the ExclusiveDevice. 10 bytes = 80 clocks. - let cs = Output::new(cs_pin, Level::High); + let cs = Output::new(p.cs, Level::High); if let Err(e) = spi_bus.blocking_write(&[0xFFu8; 10]) { defmt::warn!("SD power-up clocks failed: {:?}", defmt::Debug2Format(&e)); } @@ -484,30 +370,24 @@ async fn main(spawner: Spawner) { init_heap(); - let p = { - use embassy_rp::clocks::ClockConfig; - let mut clk = - ClockConfig::system_freq(TARGET_SYS_HZ).expect("valid PLL params for target clock"); - clk.core_voltage = TARGET_CORE_VOLTAGE; - embassy_rp::init(embassy_rp::config::Config::new(clk)) - }; + let board = Board::init(); wdt::init( - Watchdog::new(p.WATCHDOG), + Watchdog::new(board.watchdog), Duration::from_millis(WATCHDOG_WINDOW_MS), ); info!( "rustyboy-pico2w v{} starting @{}MHz", FIRMWARE_VERSION, - TARGET_SYS_HZ / 1_000_000 + Board::sys_hz() / 1_000_000 ); // Commit any pending crash record as the VERY FIRST thing after clocks are // up. Flash only needs the system clock — no display, SD, or other // peripherals required. Moving this before HwDisplay::new() ensures the // record is written even if the crash happens during the splash screen. - let mut onboard_flash = new_onboard_flash(p.FLASH); + let mut onboard_flash = new_onboard_flash(board.flash); if crash::storage::check_and_commit(&mut onboard_flash) { defmt::warn!("crash: committed crash record from previous boot"); } @@ -520,24 +400,18 @@ async fn main(spawner: Spawner) { // time it returns the 100 ms minimum off-time is satisfied. Setting GP20 // high immediately after lets the 2.7 s splash cover the 250 ms power-up // window — no added delay visible to the user. - let mut sd_pwr = Output::new(p.PIN_20, Level::Low); + let mut sd_pwr = Output::new(board.sd_power, Level::Low); - // GP8=DC GP9=CS GP10=CLK GP11=MOSI GP12=RST GP13=BL - let mut hw_disp = HwDisplay::new( - p.SPI1, p.PIN_10, p.PIN_11, p.PIN_9, p.PIN_8, p.PIN_12, p.PIN_13, - ); + let mut display_periphs = board.display; + let mut hw_disp = HwDisplay::new(&mut display_periphs); sd_pwr.set_high(); // SD module now has ≥265 ms off-time behind it; splash provides the 250 ms power-up window info!("starting splash"); hw_disp.splash().await; - drop(hw_disp); + drop(hw_disp); // ends the borrow of display_periphs - // GP21=Up GP22=Down GP26=Left GP27=Right - // GP0=A GP1=B GP2=Start GP3=Select - let mut input = InputHandler::new( - p.PIN_21, p.PIN_22, p.PIN_26, p.PIN_27, p.PIN_0, p.PIN_1, p.PIN_2, p.PIN_3, - ); + let mut input = InputHandler::new(board.buttons); - let mut sd_mgr = init_sd_card(p.PIN_17, p.SPI0, p.PIN_6, p.PIN_7, p.PIN_4, p.PIN_5); + let mut sd_mgr = init_sd_card(board.sd); // Check for unread crash records so menus can show the crash-report badge. // (check_and_commit already ran earlier — before the splash.) @@ -549,38 +423,9 @@ async fn main(spawner: Spawner) { // Check whether a ROM is already staged in flash. let staged = probe_staged_rom(&mut onboard_flash); - let Pio { - mut common, sm0, .. - } = Pio::new(p.PIO0, Irqs); - let i2s_prog = PioI2sOutProgram::new(&mut common); - let mut i2s = PioI2sOut::new( - &mut common, - sm0, - p.DMA_CH0, - Irqs, - p.PIN_16, - p.PIN_14, - p.PIN_15, - SAMPLE_RATE, - 16, - &i2s_prog, - ); - i2s.start(); - - // SAFETY: hw_disp was dropped above; SPI1 and all display pins are free. - let mut game_disp = unsafe { - GameDisplay::new_after_splash( - PIN_10::steal(), - PIN_11::steal(), - PIN_9::steal(), - PIN_8::steal(), - PIN_12::steal(), - PIN_13::steal(), - SPI1::steal(), - p.DMA_CH1, - Irqs, - ) - }; + let mut i2s = init_i2s(board.audio, Irqs); + + let mut game_disp = GameDisplay::new_after_splash(display_periphs, Irqs); let mut audio_buffers = AudioBuffers::new(); let mut audio_samples = Vec::with_capacity(2048); @@ -609,7 +454,7 @@ async fn main(spawner: Spawner) { // would fault (MSTKERR false positive). See // docs/investigations/memory-barrier-investigation-plan.md. let mut gb: Box = - Box::new(PicoGameBoy::with_cartridge(p.CORE1, Box::new(cart))); + Box::new(PicoGameBoy::with_cartridge(board.core1, Box::new(cart))); if let Some(rom_id) = info.rom_id { restore_saves_on_boot(&sd_mgr, &rom_id, &mut gb); } @@ -637,7 +482,7 @@ async fn main(spawner: Spawner) { wifi_periphs: None, }; let next = MainMenuState::new(&mut game_disp, &stub_app).await; - (AppState::MainMenu(next), None, None, None, Some(p.CORE1)) + (AppState::MainMenu(next), None, None, None, Some(board.core1)) } } } @@ -661,7 +506,7 @@ async fn main(spawner: Spawner) { None, None, None, - Some(p.CORE1), + Some(board.core1), ) } }; @@ -676,18 +521,6 @@ async fn main(spawner: Spawner) { // bug #5 wild store runs. See docs/investigations/memory-barrier-investigation-plan.md. let mut gameboy: Option> = gameboy_init; - let wifi_periphs = Some(WifiPeriphs { - pwr: p.PIN_23, - dio: p.PIN_24, - cs: p.PIN_25, - clk: p.PIN_29, - pio1: p.PIO1, - dma_ch2: p.DMA_CH2, - dma_ch3: p.DMA_CH3, - pio_irqs: WifiIrqs, - dma_irqs: Irqs, - }); - let mut app = App { state: initial_state, next_state: None, @@ -698,7 +531,7 @@ async fn main(spawner: Spawner) { core1: core1_token, crash_pending, spawner, - wifi_periphs, + wifi_periphs: Some(board.wifi), }; // Runs after the watchdog is armed and before the main loop's first feed, so // on a dead card an acquisition timeout here would itself trip the watchdog.