Add new driver implementations and workspace updates

This commit is contained in:
Kevin Thomas
2026-03-27 11:18:29 -04:00
parent 1c02ebd76e
commit bef5e91fbf
7844 changed files with 30810 additions and 2 deletions
+207
View File
@@ -0,0 +1,207 @@
//! @file board.rs
//! @brief Board-level HAL helpers for the flash driver
//! @author Kevin Thomas
//! @date 2025
//!
//! MIT License
//!
//! Copyright (c) 2025 Kevin Thomas
//!
//! Permission is hereby granted, free of charge, to any person obtaining a copy
//! of this software and associated documentation files (the "Software"), to deal
//! in the Software without restriction, including without limitation the rights
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//! copies of the Software, and to permit persons to whom the Software is
//! furnished to do so, subject to the following conditions:
//!
//! The above copyright notice and this permission notice shall be included in
//! all copies or substantial portions of the Software.
//!
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//! SOFTWARE.
// Flash driver pure-logic functions and constants
use crate::flash_driver;
// Rate extension trait for .Hz() baud rate construction
use fugit::RateExtU32;
// Clock trait for accessing system clock frequency
use hal::Clock;
// GPIO pin types and function selectors
use hal::gpio::{FunctionNull, FunctionUart, Pin, PullDown, PullNone};
// ROM data flash functions for low-level flash operations
use hal::rom_data;
// UART configuration and peripheral types
use hal::uart::{DataBits, Enabled, StopBits, UartConfig, UartPeripheral};
// Alias our HAL crate
#[cfg(rp2350)]
use rp235x_hal as hal;
#[cfg(rp2040)]
use rp2040_hal as hal;
/// External crystal frequency in Hz (12 MHz).
pub(crate) const XTAL_FREQ_HZ: u32 = 12_000_000u32;
/// UART baud rate in bits per second.
pub(crate) const UART_BAUD: u32 = 115_200;
/// Type alias for the configured TX pin (GPIO 0, UART function, no pull).
pub(crate) type TxPin = Pin<hal::gpio::bank0::Gpio0, FunctionUart, PullNone>;
/// Type alias for the configured RX pin (GPIO 1, UART function, no pull).
pub(crate) type RxPin = Pin<hal::gpio::bank0::Gpio1, FunctionUart, PullNone>;
/// Type alias for the default TX pin state from `Pins::new()`.
pub(crate) type TxPinDefault = Pin<hal::gpio::bank0::Gpio0, FunctionNull, PullDown>;
/// Type alias for the default RX pin state from `Pins::new()`.
pub(crate) type RxPinDefault = Pin<hal::gpio::bank0::Gpio1, FunctionNull, PullDown>;
/// Type alias for the fully-enabled UART0 peripheral with TX/RX pins.
pub(crate) type EnabledUart = UartPeripheral<Enabled, hal::pac::UART0, (TxPin, RxPin)>;
/// Initialise system clocks and PLLs from the external 12 MHz crystal.
///
/// # Arguments
///
/// * `xosc` - XOSC peripheral singleton.
/// * `clocks` - CLOCKS peripheral singleton.
/// * `pll_sys` - PLL_SYS peripheral singleton.
/// * `pll_usb` - PLL_USB peripheral singleton.
/// * `resets` - Mutable reference to the RESETS peripheral.
/// * `watchdog` - Mutable reference to the watchdog timer.
///
/// # Returns
///
/// Configured clocks manager.
///
/// # Panics
///
/// Panics if clock initialisation fails.
pub(crate) fn init_clocks(
xosc: hal::pac::XOSC,
clocks: hal::pac::CLOCKS,
pll_sys: hal::pac::PLL_SYS,
pll_usb: hal::pac::PLL_USB,
resets: &mut hal::pac::RESETS,
watchdog: &mut hal::Watchdog,
) -> hal::clocks::ClocksManager {
hal::clocks::init_clocks_and_plls(
XTAL_FREQ_HZ, xosc, clocks, pll_sys, pll_usb, resets, watchdog,
)
.unwrap()
}
/// Unlock the GPIO bank and return the pin set.
///
/// # Arguments
///
/// * `io_bank0` - IO_BANK0 peripheral singleton.
/// * `pads_bank0` - PADS_BANK0 peripheral singleton.
/// * `sio` - SIO peripheral singleton.
/// * `resets` - Mutable reference to the RESETS peripheral.
///
/// # Returns
///
/// GPIO pin set for the entire bank.
pub(crate) fn init_pins(
io_bank0: hal::pac::IO_BANK0,
pads_bank0: hal::pac::PADS_BANK0,
sio: hal::pac::SIO,
resets: &mut hal::pac::RESETS,
) -> hal::gpio::Pins {
let sio = hal::Sio::new(sio);
hal::gpio::Pins::new(io_bank0, pads_bank0, sio.gpio_bank0, resets)
}
/// Initialise UART0 for serial output (stdio equivalent).
///
/// # Arguments
///
/// * `uart0` - PAC UART0 peripheral singleton.
/// * `tx_pin` - GPIO pin to use as UART0 TX (GPIO 0).
/// * `rx_pin` - GPIO pin to use as UART0 RX (GPIO 1).
/// * `resets` - Mutable reference to the RESETS peripheral.
/// * `clocks` - Reference to the initialised clock configuration.
///
/// # Returns
///
/// Enabled UART0 peripheral ready for blocking writes.
///
/// # Panics
///
/// Panics if the HAL cannot achieve the requested baud rate.
pub(crate) fn init_uart(
uart0: hal::pac::UART0,
tx_pin: TxPinDefault,
rx_pin: RxPinDefault,
resets: &mut hal::pac::RESETS,
clocks: &hal::clocks::ClocksManager,
) -> EnabledUart {
let pins = (
tx_pin.reconfigure::<FunctionUart, PullNone>(),
rx_pin.reconfigure::<FunctionUart, PullNone>(),
);
let cfg = UartConfig::new(UART_BAUD.Hz(), DataBits::Eight, None, StopBits::One);
UartPeripheral::new(uart0, pins, resets)
.enable(cfg, clocks.peripheral_clock.freq())
.unwrap()
}
/// Erase one 4096-byte sector and write data to on-chip flash.
///
/// Disables interrupts, transitions the flash device out of XIP mode,
/// erases the sector at `flash_offset`, programs `data` into it, flushes
/// the cache, re-enters XIP mode, and restores interrupts. This mirrors
/// the C demo's `flash_driver_write()`.
///
/// # Arguments
///
/// * `flash_offset` - Byte offset from the start of flash (must be sector-aligned).
/// * `data` - Data buffer to write (length must be a multiple of 256).
///
/// # Safety
///
/// Caller must ensure no other core or DMA is accessing flash/XIP during
/// this operation.
pub(crate) fn flash_write(flash_offset: u32, data: &[u8]) {
let len = data.len();
cortex_m::interrupt::free(|_| unsafe {
rom_data::connect_internal_flash();
rom_data::flash_exit_xip();
rom_data::flash_range_erase(
flash_offset,
flash_driver::FLASH_SECTOR_SIZE as usize,
flash_driver::FLASH_SECTOR_SIZE,
0x20,
);
rom_data::flash_range_program(flash_offset, data.as_ptr(), len);
rom_data::flash_flush_cache();
rom_data::flash_enter_cmd_xip();
});
}
/// Read bytes from on-chip flash via the XIP memory map.
///
/// Flash is memory-mapped starting at XIP_BASE (0x10000000). This
/// function copies `out.len()` bytes from the XIP address corresponding
/// to `flash_offset` into `out`, matching the C demo's
/// `flash_driver_read()`.
///
/// # Arguments
///
/// * `flash_offset` - Byte offset from the start of flash.
/// * `out` - Destination buffer.
pub(crate) fn flash_read(flash_offset: u32, out: &mut [u8]) {
let addr = (flash_driver::XIP_BASE + flash_offset) as *const u8;
for (i, byte) in out.iter_mut().enumerate() {
*byte = unsafe { core::ptr::read_volatile(addr.add(i)) };
}
}
// End of file
+205
View File
@@ -0,0 +1,205 @@
//! @file flash_driver.rs
//! @brief Pure-logic flash driver (host-testable, no HAL)
//! @author Kevin Thomas
//! @date 2025
//!
//! MIT License
//!
//! Copyright (c) 2025 Kevin Thomas
//!
//! Permission is hereby granted, free of charge, to any person obtaining a copy
//! of this software and associated documentation files (the "Software"), to deal
//! in the Software without restriction, including without limitation the rights
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//! copies of the Software, and to permit persons to whom the Software is
//! furnished to do so, subject to the following conditions:
//!
//! The above copyright notice and this permission notice shall be included in
//! all copies or substantial portions of the Software.
//!
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//! SOFTWARE.
/// Total on-chip flash size in bytes (4 MB).
pub const FLASH_SIZE_BYTES: u32 = 4 * 1024 * 1024;
/// Flash sector size in bytes (4096).
pub const FLASH_SECTOR_SIZE: u32 = 4096;
/// Flash page size in bytes (256).
pub const FLASH_PAGE_SIZE: u32 = 256;
/// Flash target offset: last sector of flash.
pub const FLASH_TARGET_OFFSET: u32 = FLASH_SIZE_BYTES - FLASH_SECTOR_SIZE;
/// Write buffer length matching the C demo (one page = 256 bytes).
pub const FLASH_WRITE_LEN: usize = FLASH_PAGE_SIZE as usize;
/// XIP base address where flash is memory-mapped.
pub const XIP_BASE: u32 = 0x1000_0000;
/// Demo string written to flash, matching the C demo exactly.
pub const DEMO_MSG: &[u8] = b"Embedded Hacking flash driver demo";
/// Prepare a write buffer with 0xFF fill and the demo string at the start.
///
/// Mirrors the C demo's `_prepare_write_buf()` function. The buffer is
/// filled with 0xFF (erased flash state), then the demo string including
/// its NUL terminator is copied to the beginning.
///
/// # Arguments
///
/// * `buf` - Output buffer (should be `FLASH_WRITE_LEN` bytes).
///
/// # Returns
///
/// Number of meaningful bytes (string length + NUL terminator).
pub fn prepare_write_buf(buf: &mut [u8]) -> usize {
for b in buf.iter_mut() {
*b = 0xFF;
}
let msg_with_nul = DEMO_MSG.len() + 1;
let n = msg_with_nul.min(buf.len());
let copy_len = DEMO_MSG.len().min(n);
buf[..copy_len].copy_from_slice(&DEMO_MSG[..copy_len]);
if copy_len < n {
buf[copy_len] = 0x00;
}
n
}
/// Format the "Flash readback: <string>\r\n" message into `buf`.
///
/// Reads from `read_data` up to the first NUL byte (or end of slice)
/// and formats the output message matching the C demo's printf.
///
/// # Arguments
///
/// * `buf` - Output buffer (should be >= 64 bytes).
/// * `read_data` - Data read back from flash.
///
/// # Returns
///
/// Number of bytes written to `buf`.
pub fn format_readback(buf: &mut [u8], read_data: &[u8]) -> usize {
let prefix = b"Flash readback: ";
let suffix = b"\r\n";
let mut pos = 0usize;
// Write prefix
let n = prefix.len().min(buf.len());
buf[..n].copy_from_slice(&prefix[..n]);
pos += n;
// Find NUL terminator in read_data
let str_len = read_data.iter().position(|&b| b == 0).unwrap_or(read_data.len());
let copy_len = str_len.min(buf.len().saturating_sub(pos));
buf[pos..pos + copy_len].copy_from_slice(&read_data[..copy_len]);
pos += copy_len;
// Write suffix
let n = suffix.len().min(buf.len().saturating_sub(pos));
buf[pos..pos + n].copy_from_slice(&suffix[..n]);
pos += n;
pos
}
#[cfg(test)]
mod tests {
// Import all parent module items
use super::*;
#[test]
fn flash_size_is_4mb() {
assert_eq!(FLASH_SIZE_BYTES, 4 * 1024 * 1024);
}
#[test]
fn sector_size_is_4096() {
assert_eq!(FLASH_SECTOR_SIZE, 4096);
}
#[test]
fn page_size_is_256() {
assert_eq!(FLASH_PAGE_SIZE, 256);
}
#[test]
fn target_offset_is_last_sector() {
assert_eq!(FLASH_TARGET_OFFSET, FLASH_SIZE_BYTES - FLASH_SECTOR_SIZE);
}
#[test]
fn write_len_matches_page_size() {
assert_eq!(FLASH_WRITE_LEN, 256);
}
#[test]
fn xip_base_address() {
assert_eq!(XIP_BASE, 0x1000_0000);
}
#[test]
fn prepare_write_buf_fills_0xff() {
let mut buf = [0u8; FLASH_WRITE_LEN];
prepare_write_buf(&mut buf);
// Bytes after the string + NUL should be 0xFF
let after = DEMO_MSG.len() + 1;
for &b in &buf[after..] {
assert_eq!(b, 0xFF);
}
}
#[test]
fn prepare_write_buf_has_demo_string() {
let mut buf = [0u8; FLASH_WRITE_LEN];
prepare_write_buf(&mut buf);
assert_eq!(&buf[..DEMO_MSG.len()], DEMO_MSG);
}
#[test]
fn prepare_write_buf_has_nul_terminator() {
let mut buf = [0u8; FLASH_WRITE_LEN];
prepare_write_buf(&mut buf);
assert_eq!(buf[DEMO_MSG.len()], 0x00);
}
#[test]
fn format_readback_matches_c_output() {
let mut read_data = [0xFFu8; FLASH_WRITE_LEN];
let msg = b"Embedded Hacking flash driver demo";
read_data[..msg.len()].copy_from_slice(msg);
read_data[msg.len()] = 0x00;
let mut buf = [0u8; 128];
let n = format_readback(&mut buf, &read_data);
assert_eq!(
&buf[..n],
b"Flash readback: Embedded Hacking flash driver demo\r\n"
);
}
#[test]
fn format_readback_empty_string() {
let read_data = [0u8; 8];
let mut buf = [0u8; 64];
let n = format_readback(&mut buf, &read_data);
assert_eq!(&buf[..n], b"Flash readback: \r\n");
}
#[test]
fn format_readback_no_nul() {
let read_data = [b'A'; 8];
let mut buf = [0u8; 64];
let n = format_readback(&mut buf, &read_data);
assert_eq!(&buf[..n], b"Flash readback: AAAAAAAA\r\n");
}
#[test]
fn demo_msg_matches_c_string() {
assert_eq!(DEMO_MSG, b"Embedded Hacking flash driver demo");
}
}
// End of file
+9
View File
@@ -0,0 +1,9 @@
//! @file lib.rs
//! @brief Library root for the flash driver crate
//! @author Kevin Thomas
//! @date 2025
#![no_std]
// Flash driver module
pub mod flash_driver;
+110
View File
@@ -0,0 +1,110 @@
//! @file main.rs
//! @brief On-chip flash write/read demo using flash_driver.rs
//! @author Kevin Thomas
//! @date 2025
//!
//! MIT License
//!
//! Copyright (c) 2025 Kevin Thomas
//!
//! Permission is hereby granted, free of charge, to any person obtaining a copy
//! of this software and associated documentation files (the "Software"), to deal
//! in the Software without restriction, including without limitation the rights
//! to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//! copies of the Software, and to permit persons to whom the Software is
//! furnished to do so, subject to the following conditions:
//!
//! The above copyright notice and this permission notice shall be included in
//! all copies or substantial portions of the Software.
//!
//! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//! IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//! FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//! AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//! LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//! OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//! SOFTWARE.
//!
//! -----------------------------------------------------------------------------
//!
//! Demonstrates on-chip flash read/write using the flash driver
//! (flash_driver.rs). A string is written to the last sector of flash
//! and then read back to verify. The result is printed over UART.
//!
//! Wiring:
//! No external wiring required
#![no_std]
#![no_main]
// Board-level helpers: constants, type aliases, and init functions
mod board;
// Flash driver module — suppress warnings for unused public API functions
#[allow(dead_code)]
mod flash_driver;
// Debugging output over RTT
use defmt_rtt as _;
// Panic handler for RISC-V targets
#[cfg(target_arch = "riscv32")]
use panic_halt as _;
// Panic handler for ARM targets
#[cfg(target_arch = "arm")]
use panic_probe as _;
// HAL entry-point macro
use hal::entry;
// Alias our HAL crate
#[cfg(rp2350)]
use rp235x_hal as hal;
#[cfg(rp2040)]
use rp2040_hal as hal;
// Second-stage boot loader for RP2040
#[unsafe(link_section = ".boot2")]
#[used]
#[cfg(rp2040)]
pub static BOOT2: [u8; 256] = rp2040_boot2::BOOT_LOADER_W25Q080;
// Boot metadata for the RP2350 Boot ROM
#[unsafe(link_section = ".start_block")]
#[used]
#[cfg(rp2350)]
pub static IMAGE_DEF: hal::block::ImageDef = hal::block::ImageDef::secure_exe();
/// Application entry point for the on-chip flash demo.
#[entry]
fn main() -> ! {
let mut pac = hal::pac::Peripherals::take().unwrap();
let clocks = board::init_clocks(
pac.XOSC, pac.CLOCKS, pac.PLL_SYS, pac.PLL_USB, &mut pac.RESETS,
&mut hal::Watchdog::new(pac.WATCHDOG),
);
let pins = board::init_pins(pac.IO_BANK0, pac.PADS_BANK0, pac.SIO, &mut pac.RESETS);
let uart = board::init_uart(pac.UART0, pins.gpio0, pins.gpio1, &mut pac.RESETS, &clocks);
let mut write_buf = [0u8; flash_driver::FLASH_WRITE_LEN];
flash_driver::prepare_write_buf(&mut write_buf);
board::flash_write(flash_driver::FLASH_TARGET_OFFSET, &write_buf);
let mut read_buf = [0u8; flash_driver::FLASH_WRITE_LEN];
board::flash_read(flash_driver::FLASH_TARGET_OFFSET, &mut read_buf);
let mut out = [0u8; 128];
let n = flash_driver::format_readback(&mut out, &read_buf);
uart.write_full_blocking(&out[..n]);
loop {
cortex_m::asm::wfe();
}
}
// Picotool binary info metadata
#[unsafe(link_section = ".bi_entries")]
#[used]
pub static PICOTOOL_ENTRIES: [hal::binary_info::EntryAddr; 5] = [
hal::binary_info::rp_cargo_bin_name!(),
hal::binary_info::rp_cargo_version!(),
hal::binary_info::rp_program_description!(c"On-chip Flash Demo"),
hal::binary_info::rp_cargo_homepage_url!(),
hal::binary_info::rp_program_build_attribute!(),
];
// End of file