### Development Environment Setup Flowchart Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Mermaid diagram showing the setup components: Rust toolchain, targets, flashing tools, and configuration files. Use to visualize the installation steps. ```mermaid flowchart TD subgraph "Development Environment Setup" RUST["rustup/cargo"] TARGETS["Rust Targets - thumbv6m-none-eabi (RP2040) - thumbv8m.main-none-eabihf (RP235x ARM) - riscv32imac-unknown-none-elf (RP235x RISC-V)"] TOOLS["Firmware Flashing Tools"] ELF2UF2["elf2uf2-rs (USB Bootloader)"] PROBERS["probe-rs (JTAG/SWD)"] PICOTOOL["picotool (Command-line)"] CONFIG["Project Configuration"] CARGO_CONFIG[".cargo/config.toml"] MEMORY["memory.x"] end RUST --> TARGETS TOOLS --> ELF2UF2 TOOLS --> PROBERS TOOLS --> PICOTOOL CONFIG --> CARGO_CONFIG CONFIG --> MEMORY ``` -------------------------------- ### Example Structure Diagram (Mermaid) Source: https://deepwiki.com/rp-rs/rp-hal/2.3-example-programs Mermaid diagram illustrating the consistent structure of example programs: documentation header, HAL setup and initialization, feature demonstration, and main loop. Shows the HAL setup components (boot code, clock configuration, pin configuration, peripheral initialization) and common patterns (rp2040_hal::entry, watchdog, SIO, resets). ```mermaid graph TB subgraph "Example Structure" HEADER["Documentation Header"] SETUP["HAL Setup & Initialization"] FEATURE["Feature Demonstration"] LOOP["Main Loop"] end HEADER --> SETUP SETUP --> FEATURE FEATURE --> LOOP subgraph "HAL Setup Components" BOOT["Boot Code"] CLOCKS["Clock Configuration"] PINS["Pin Configuration"] PERIPH["Peripheral Initialization"] end SETUP --> BOOT SETUP --> CLOCKS SETUP --> PINS SETUP --> PERIPH subgraph "Common Patterns" ENTRY["rp2040_hal::entry"] WATCHDOG["Watchdog Configuration"] SIO["SIO Configuration"] RESETS["Peripheral Resets"] end BOOT --> ENTRY CLOCKS --> WATCHDOG PINS --> SIO PERIPH --> RESETS ``` -------------------------------- ### Dynamic Channel Example: Configure and Start DMA Transfer Source: https://deepwiki.com/rp-rs/rp-hal/5.2-dma-system Shows how to take a dynamic DMA channel, configure a single-buffer transfer, start it, wait for completion, and return the channel to the pool. Requires explicit channel management and error handling after the transfer. ```rust // Get a dynamic channel let ch0 = state.channels.ch0.take().expect("Could not take Dyn DMA channel"); // Configure and start transfer let rx_buffer = [0u8; 10]; let tx_buffer = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let tx_transfer = hal::dma::single_buffer::Config::new(ch0, tx_buffer, rx_buffer); let tx_started = tx_transfer.start(); // Wait for completion let (newch0, tx_buffer, rx_buffer) = tx_started.wait(); // Return channel to the pool state.channels.ch0.replace(newch0); ``` -------------------------------- ### Blinking LED with rp-hal Source: https://deepwiki.com/rp-rs/rp-hal/2-getting-started A minimal example to get started with a blinking LED using rp-hal. It demonstrates the typical initialization pattern: access peripherals, initialize watchdog and clocks, set up GPIO pins, and run the main loop. The example uses a 12 MHz crystal and toggles the LED every 500 ms. ```rust #![no_std] #![no_main] use panic_halt as _; use rp2040_hal as hal; // Boot loader #[link_section = ".boot2"] #[used] pub static BOOT2: [u8; 256] = rp2040_boot2::BOOT_LOADER_GENERIC_03H; // Entry point #[hal::entry] fn main() -> ! { // Get access to the device peripherals let mut peripherals = hal::pac::Peripherals::take().unwrap(); // Configure watchdog and clocks let mut watchdog = hal::Watchdog::new(peripherals.WATCHDOG); let clocks = hal::clocks::init_clocks_and_plls( 12_000_000, // 12 MHz crystal peripherals.XOSC, peripherals.CLOCKS, peripherals.PLL_SYS, peripherals.PLL_USB, &mut peripherals.RESETS, &mut watchdog, ).unwrap(); // Initialize GPIO pins let sio = hal::Sio::new(peripherals.SIO); let pins = hal::gpio::Pins::new( peripherals.IO_BANK0, peripherals.PADS_BANK0, sio.gpio_bank0, &mut peripherals.RESETS, ); // Configure LED pin as an output let mut led_pin = pins.gpio25.into_push_pull_output(); // Create a timer let timer = hal::Timer::new(peripherals.TIMER, &mut peripherals.RESETS, &clocks); // Main loop loop { led_pin.set_high().unwrap(); hal::Clock::delay_ms(&clocks.system_clock, 500); led_pin.set_low().unwrap(); hal::Clock::delay_ms(&clocks.system_clock, 500); } } ``` -------------------------------- ### Build commands for RP2040 and RP235x examples Source: https://deepwiki.com/rp-rs/rp-hal/2.3-example-programs Use these commands to build an example for the specified target. Replace with the actual example name. The RP2040 target is thumbv6m-none-eabi and the RP235x target is thumbv8m.main-none-eabihf. ```bash # For RP2040 examples cargo build --target thumbv6m-none-eabi --release --example # For RP235x examples cargo build --target thumbv8m.main-none-eabihf --release --example ``` -------------------------------- ### Build blinky example for RP2040 Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Builds the blinky example for RP2040. Requires the rp2040-hal-examples directory. ```bash # For RP2040 cd rp2040-hal-examples cargo build --bin blinky ``` -------------------------------- ### Project setup options flowchart Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Mermaid flowchart showing the two project setup options: using the RP2040 Project Template or custom setup with configuration files. ```mermaid flowchart TD subgraph "Project Setup Options" START["New RP-HAL Project"] TEMPLATE["Use RP2040 Project Template"] CUSTOM["Custom Setup"] CONFIG["Configure Project Files"] CARGO_CONFIG[".cargo/config.toml"] MEMORY["memory.x"] CODE["Write Application Code"] BUILD["Build & Flash"] end START --> TEMPLATE START --> CUSTOM TEMPLATE --> CODE CUSTOM --> CONFIG CONFIG --> CARGO_CONFIG CONFIG --> MEMORY CONFIG --> CODE CODE --> BUILD ``` -------------------------------- ### Pin Configuration Examples (Rust) Source: https://deepwiki.com/rp-rs/rp-hal/3-core-hal-concepts Rust code examples showing how to configure pins for UART, SPI, and push-pull output using the RP-HAL GPIO API. ```rust // Configure pins for UART let uart_pins = ( pins.gpio0.into_function(), // UART TX pins.gpio1.into_function(), // UART RX ); // Configure pins for SPI let spi_copi = pins.gpio7.into_function::(); let spi_cipo = pins.gpio4.into_function::(); let spi_sclk = pins.gpio6.into_function::(); // Configure a pin as a push-pull output for SPI CS let spi_cs = pins.gpio8.into_push_pull_output_in_state(PinState::High); ``` -------------------------------- ### Install Rust with rustup Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Downloads and installs Rust using rustup. Run this command in a terminal if Rust is not already installed. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Install essential tools for building and flashing Source: https://deepwiki.com/rp-rs/rp-hal/2-getting-started Installs elf2uf2-rs for creating UF2 images for the USB bootloader and probe-rs-tools for flashing over SWD pins using a JTAG probe. Use these tools to build and flash rp-hal applications. ```bash # Tool for creating UF2 images for the USB bootloader cargo install elf2uf2-rs --locked # Tool for flashing over SWD pins using a JTAG probe cargo install --locked probe-rs-tools ``` -------------------------------- ### Run RISC-V Example with cargo alias Source: https://deepwiki.com/rp-rs/rp-hal/2.2-programming-workflows Builds and flashes the blinky example for RISC-V mode using the run-riscv alias. ```bash cargo run-riscv --bin blinky ``` -------------------------------- ### Build for ARM Mode (direct) Source: https://deepwiki.com/rp-rs/rp-hal/2.2-programming-workflows Builds the blinky example for ARM mode using the thumbv8m.main-none-eabihf target. ```bash cargo build --target thumbv8m.main-none-eabihf --bin blinky ``` -------------------------------- ### SPI Example Components Flowchart Source: https://deepwiki.com/rp-rs/rp-hal/2.3-example-programs A Mermaid flowchart illustrating the components and flow of an SPI example, including bus configuration, device creation, driver implementation, and transactions. It shows the setup of the SPI bus, chip select pin, exclusive device, and read/write operations. ```mermaid flowchart TD subgraph "SPI Example Components" SPI_INIT["SPI Initialization"] BUS_CONFIG["Bus Configuration"] DEVICE["SPI Device Creation"] DRIVER["Device Driver Implementation"] TRANSACTION["SPI Transactions"] end SPI_INIT --> BUS_CONFIG BUS_CONFIG --> DEVICE DEVICE --> DRIVER DRIVER --> TRANSACTION subgraph "Example: SPI Bus with Device Driver" BUS_SETUP["Setup SPI Bus - Configure pins - Set clock speed - Set SPI mode"] CS_PIN["Configure Chip Select Pin"] EXCL_DEV["Create ExclusiveDevice"] OPERATION["Perform Read/Write Operations"] end BUS_CONFIG --> BUS_SETUP DEVICE --> CS_PIN CS_PIN --> EXCL_DEV EXCL_DEV --> OPERATION ``` -------------------------------- ### Install Rust toolchain and targets for RP2040 and RP235x Source: https://deepwiki.com/rp-rs/rp-hal/2-getting-started Updates Rust and adds the required compilation targets for RP2040 (thumbv6m-none-eabi) and RP235x in both ARM mode (thumbv8m.main-none-eabihf) and RISC-V mode (riscv32imac-unknown-none-elf). Run these commands before starting any rp-hal project. ```bash rustup self update rustup update stable rustup target add thumbv6m-none-eabi # For RP2040 rustup target add thumbv8m.main-none-eabihf # For RP235x (ARM mode) rustup target add riscv32imac-unknown-none-elf # For RP235x (RISC-V mode) ``` -------------------------------- ### Initialization Flow Diagram (Mermaid) Source: https://deepwiki.com/rp-rs/rp-hal/1-overview Mermaid graph showing the initialization flow from Peripherals::take() through reset control, clock setup, and pin initialization. ```mermaid graph TB PERIPHERALS["Peripherals::take()"] --> RESETS["Reset Control"] RESETS --> WATCHDOG["Watchdog::new"] RESETS --> OSCILLATORS["Setup Oscillators"] OSCILLATORS --> XOSC["XOSC (Crystal)"] OSCILLATORS --> ROSC["ROSC (Ring)"] XOSC --> CLOCKS_INIT["init_clocks_and_plls"] ROSC --> CLOCKS_INIT WATCHDOG --> CLOCKS_INIT CLOCKS_INIT --> CLOCKS_MANAGER["ClocksManager"] CLOCKS_MANAGER --> SYS_CLOCK["System Clock"] CLOCKS_MAGER --> USB_CLOCK["USB Clock"] CLOCKS_MANAGER --> PERI_CLOCK["Peripheral Clock"] RESETS --> SIO["Sio::new()"] SIO --> PINS["Pins::new()"] CLOCKS_MANAGER --> PERIPHERALS_INIT["Initialize Peripherals"] PINS --> PERIPHERALS_INIT ``` -------------------------------- ### Build for ARM Mode (cargo alias) Source: https://deepwiki.com/rp-rs/rp-hal/2.2-programming-workflows Builds the blinky example for ARM mode using the build-arm alias. ```bash cargo build-arm --bin blinky ``` -------------------------------- ### Build for RISC-V Mode (direct) Source: https://deepwiki.com/rp-rs/rp-hal/2.2-programming-workflows Builds the blinky example for RISC-V mode using the riscv32imac-unknown-none-elf target. ```bash cargo build --target riscv32imac-unknown-none-elf --bin blinky ``` -------------------------------- ### Install probe-rs tools Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Installs the probe-rs tools via cargo, which allow flashing and debugging via SWD/JTAG probes. ```bash cargo install --locked probe-rs-tools ``` -------------------------------- ### Initialization Flow Diagram (Mermaid) Source: https://deepwiki.com/rp-rs/rp-hal Mermaid diagram showing the initialization flow from Peripherals::take() through clock setup to pin initialization. ```mermaid graph TB PERIPHERALS["Peripherals::take()"] --> RESETS["Reset Control"] RESETS --> WATCHDOG["Watchdog::new"] RESETS --> OSCILLATORS["Setup Oscillators"] OSCILLATORS --> XOSC["XOSC (Crystal)"] OSCILLATORS --> ROSC["ROSC (Ring)"] XOSC --> CLOCKS_INIT["init_clocks_and_plls"] ROSC --> CLOCKS_INIT WATCHDOG --> CLOCKS_INIT CLOCKS_INIT --> CLOCKS_MANAGER["ClocksManager"] CLOCKS_MANAGER --> SYS_CLOCK["System Clock"] CLOCKS_MANAGER --> USB_CLOCK["USB Clock"] CLOCKS_MANAGER --> PERI_CLOCK["Peripheral Clock"] RESETS --> SIO["Sio::new()"] SIO --> PINS["Pins::new()"] CLOCKS_MANAGER --> PERIPHERALS_INIT["Initialize Peripherals"] PINS --> PERIPHERALS_INIT ``` -------------------------------- ### Build for RISC-V Mode (cargo alias) Source: https://deepwiki.com/rp-rs/rp-hal/2.2-programming-workflows Builds the blinky example for RISC-V mode using the build-riscv alias. ```bash cargo build-riscv --bin blinky ``` -------------------------------- ### Configure .cargo/config.toml for RP235x Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Example Cargo configuration for RP235x, showing placeholders for ARM and RISC-V targets. ```toml [target.thumbv8m.main-none-eabihf] # For RP235x ARM mode # Configuration here [target.riscv32imac-unknown-none-elf] # For RP235x RISC-V mode # Configuration here ``` -------------------------------- ### Install elf2uf2-rs flashing utility Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Installs the elf2uf2-rs tool via cargo, which converts ELF files to UF2 format for flashing via USB bootloader. ```bash cargo install elf2uf2-rs --locked ``` -------------------------------- ### Flash via picotool Source: https://deepwiki.com/rp-rs/rp-hal/2.2-programming-workflows picotool flashing workflow: configure the runner with picotool load -u -v -x -t elf, then run the application. Requires entering USB bootloader mode and having picotool installed; provides additional device information and management capabilities. ```toml [target.thumbv6m-none-eabi] runner = "picotool load -u -v -x -t elf" ``` ```bash cargo run --release ``` -------------------------------- ### Clone the rp-hal repository Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Clones the rp-hal repository and changes into the rp-hal directory. This is the first step to verify the installation. ```bash git clone https://github.com/rp-rs/rp-hal.git cd rp-hal ``` -------------------------------- ### Example Test Structure for On-Target Tests Source: https://deepwiki.com/rp-rs/rp-hal/6.2-on-target-testing Shows the required structure for a new on-target test file, including no_std/no_main attributes, imports for defmt_rtt, defmt_test, panic_probe, and the appropriate HAL crate based on the rp2040 or rp235x feature. Includes boot code for rp2040, a State struct, and a test module with #[init] and #[test] functions. ```rust #![no_std] #![no_main] #![cfg(test)] // Imports use defmt_rtt as _; use defmt_test as _; use panic_probe as _; #[cfg(feature = "rp2040")] use rp2040_hal as hal; #[cfg(feature = "rp235x")] use rp235x_hal as hal; // Boot code section #[cfg(feature = "rp2040")] #[link_section = ".boot2"] #[used] pub static BOOT2: [u8; 256] = rp2040_boot2::BOOT_LOADER_GENERIC_03H; // Test state struct State { // Resources needed for your tests } // Tests module #[defmt_test::tests] mod tests { use crate::State; // Setup function #[init] fn setup() -> State { // Initialize hardware and return State } // Test function #[test] fn your_test(state: &mut State) { // Test operations // Assert expected results } } ``` -------------------------------- ### SPI State Pattern: Uninitialized to Enabled Source: https://deepwiki.com/rp-rs/rp-hal/3-core-hal-concepts This example shows the type-state pattern for SPI. First, create the SPI bus in the uninitialized state, then call `init` to transition to the enabled state. The `init` method requires the reset controller, a clock frequency, and a SPI mode, and returns the bus in the enabled state. ```rust // Uninitialized state let spi_bus = hal::spi::Spi::<_, _, _, 8>::new(p.SPI0, (spi_copi, spi_cipo, spi_sclk)); // Transition to enabled state let spi_bus = spi_bus.init( &mut p.RESETS, clocks.peripheral_clock.freq(), 16.MHz(), embedded_hal::spi::MODE_0, ); ``` -------------------------------- ### Flash via UF2 bootloader with elf2uf2-rs Source: https://deepwiki.com/rp-rs/rp-hal/2.2-programming-workflows UF2 bootloader flashing workflow: install elf2uf2-rs, set it as the cargo runner for the thumbv6m-none-eabi target, then run the application. Requires entering USB bootloader mode (BOOTSEL) before running; the tool converts the ELF to UF2 and copies it to the mounted drive. ```bash cargo install elf2uf2-rs --locked ``` ```toml [target.thumbv6m-none-eabi] runner = "elf2uf2-rs -d" ``` ```bash cargo run --release ``` -------------------------------- ### UART Split Example Source: https://deepwiki.com/rp-rs/rp-hal/3-core-hal-concepts Initializes a UART peripheral and splits it into separate TX and RX interfaces. The split interfaces can be used independently, as shown by writing to TX and reading from RX. This demonstrates the ownership-safe way to pass different parts of a peripheral to different components. ```rust // Initialize UART let uart = UartPeripheral::new(p.UART0, uart_pins, &mut p.RESETS) .enable(uart_config, clocks.peripheral_clock.freq()) .unwrap(); // Split into separate TX and RX interfaces let (mut tx, mut rx) = uart.split(); // These can now be used independently tx.write_full_blocking(b"Hello"); let mut buffer = [0u8; 5]; rx.read_full_blocking(&mut buffer); ``` -------------------------------- ### Flash via probe-rs over SWD Source: https://deepwiki.com/rp-rs/rp-hal/2.2-programming-workflows probe-rs flashing workflow: install probe-rs-tools, configure the runner with --chip RP2040, verify the probe connection with probe-rs list, then run the application. Requires a debug probe connected to the SWD pins; provides direct flash access and debugging without USB bootloader mode. ```bash cargo install --locked probe-rs-tools ``` ```toml [target.thumbv6m-none-eabi] runner = "probe-rs run --chip RP2040" ``` ```bash probe-rs list ``` ```bash cargo run --release ``` -------------------------------- ### Basic FIFO ADC Sampling Source: https://deepwiki.com/rp-rs/rp-hal/4.5-adc Builds and starts an ADC FIFO with a clock divider for maximum sample rate (500ksps), reads samples while available, and stops the FIFO to regain ADC control. ```rust // Configure & start capturing to the FIFO let mut fifo = adc .build_fifo() .clock_divider(0, 0) // sample as fast as possible (500ksps) .set_channel(&mut adc_pin_0) .start(); // Read values from the FIFO while fifo.len() > 0 { let value: u16 = fifo.read(); // Process the value } // Stop sampling when done let mut adc = fifo.stop(); ``` -------------------------------- ### ADC FIFO with DMA Transfer Source: https://deepwiki.com/rp-rs/rp-hal/4.5-adc Sets up an ADC FIFO with DMA enabled, configures a DMA transfer from the FIFO to a memory buffer, starts sampling, and waits for completion. ```rust // Set up ADC FIFO with DMA enabled let mut fifo = adc.build_fifo() .set_channel(&mut adc_pin_0) .enable_dma() .prepare(); // Create in paused state // Set up DMA transfer let transfer = single_buffer::Config::new( dma.ch0, fifo.dma_read_target(), // Source buffer // Destination ).start(); // Start ADC sampling fifo.resume(); // Wait for transfer to complete let (ch, target, buffer) = transfer.wait(); ``` -------------------------------- ### Get ROM version, secure mode, chip info, and CPU info Source: https://deepwiki.com/rp-rs/rp-hal/7-rom-functions-and-hardware-specific-features Use these functions to retrieve the ROM version, check if the device is in secure mode, get chip information (device ID, wafer ID, package type), and determine the CPU architecture (ARM or RISC-V). The chip_info() and cpu_info() functions return Result types that should be handled for errors or unsupported cases. ```rust // Get ROM version and check if in secure mode let rom_version = hal::rom_data::rom_version_number(); let is_secure = hal::rom_data::is_secure_mode(); // Get chip information (device ID, wafer ID, package type) match hal::rom_data::sys_info_api::chip_info() { Ok(Some(result)) => { // Use result.device_id, result.wafer_id, etc. }, _ => { /* Handle error or unsupported case */ } } // Determine CPU architecture (ARM or RISC-V) match hal::rom_data::sys_info_api::cpu_info() { Ok(Some(result)) => { match result { CpuInfo::Arm => { /* ARM-specific code */ }, CpuInfo::Risc => { /* RISC-V specific code */ }, } }, _ => { /* Handle error or unsupported case */ } } ``` -------------------------------- ### Initialization Flow Sequence Diagram Source: https://deepwiki.com/rp-rs/rp-hal/1.2-architecture Mermaid sequence diagram showing the initialization flow of a typical rp-hal application. It illustrates the sequence of calls from the application to the rp2040-hal and rp2040-pac, including peripheral take, clock configuration, pin setup, and peripheral initialization. ```mermaid sequenceDiagram participant App as Application participant Hal as rp2040-hal participant Pac as rp2040-pac participant HW as Hardware App->>Pac: Peripherals::take() Pac-->>App: peripherals App->>Hal: Watchdog::new(peripherals.WATCHDOG) Hal-->>App: watchdog App->>Hal: init_clocks_and_plls(...) Hal->>HW: Configure XOSC Hal->>HW: Configure PLLs Hal->>HW: Configure Clock Dividers Hal-->>App: clocks_manager App->>Hal: Sio::new(peripherals.SIO) Hal-->>App: sio App->>Hal: Pins::new(...) Hal-->>App: pins App->>Hal: Timer::new(...) Hal-->>App: timer Note over App,HW: Initialize peripherals App->>Hal: gpio.into_function() Hal-->>App: configured_gpio App->>Hal: Peripheral::new(...) Hal-->>App: uninitialized_peripheral App->>Hal: uninitialized_peripheral.enable(...) Hal-->>App: initialized_peripheral ``` -------------------------------- ### Update Rust to latest stable Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Updates rustup and the stable toolchain to the latest version. Run these commands if Rust is already installed. ```bash rustup self update rustup update stable ``` -------------------------------- ### Get flash device and boot information Source: https://deepwiki.com/rp-rs/rp-hal/7-rom-functions-and-hardware-specific-features Use these functions to retrieve flash device configuration (size, chip select) and boot information. The boot_info() function returns a result with a boot_type field that can be matched against BootType variants to determine the boot mode. ```rust // Get flash device information match hal::rom_data::sys_info_api::flash_dev_info() { Ok(Some(result)) => { // Access flash size, chip select configuration, etc. }, _ => { /* Handle error or unsupported case */ } } // Get boot information match hal::rom_data::sys_info_api::boot_info() { Ok(Some(result)) => { // Check boot_type, partition, diagnostic codes, etc. let boot_mode = match result.boot_type { BootType::Normal => "Normal boot", BootType::BootSel => "Boot from BOOTSEL", BootType::RamImage => "RAM image", BootType::FlashUpdate => "Flash update", BootType::PcSp => "PC/SP boot", BootType::Unknown => "Unknown boot mode", }; }, _ => { /* Handle error or unsupported case */ } } ``` -------------------------------- ### I2C Loopback Configuration Diagram Source: https://deepwiki.com/rp-rs/rp-hal/6-development-and-testing Mermaid diagram showing the I2C loopback test setup with two I2C peripherals connected via GPIO pins. Use this to understand the physical connections required for the loopback test. ```mermaid graph LR subgraph "I2C Loopback Configuration" subgraph "I2C0 (Controller)" GPIO0["GPIO0 (SDA)"] GPIO1["GPIO1 (SCL)"] end subgraph "I2C1 (Target)" GPIO2["GPIO2 (SDA)"] GPIO3["GPIO3 (SCL)"] end end GPIO0 -- "Physical connection" --> GPIO2 GPIO1 -- "Physical connection" --> GPIO3 ``` -------------------------------- ### I2C Async Test Flow Diagram Source: https://deepwiki.com/rp-rs/rp-hal/6-development-and-testing Mermaid diagram illustrating the flow of the I2C async test, including setup, embedded_hal tests, transactions_iter, and i2c_write_iter tests, and their interaction with test state. ```mermaid graph TD subgraph "I2C Async Test Flow" SETUP["setup(): Configure hardware"] EMBEDDED_HAL["embedded_hal test: Test standard I2C ops"] TRANSACTIONS["transactions_iter test: Test transaction batching"] WRITE_ITER["i2c_write_iter test: Test iterator-based writing"] end SETUP --> EMBEDDED_HAL SETUP --> TRANSACTIONS SETUP --> WRITE_ITER subgraph "Test State" STATE["State: Contains controller & target"] TARGET_HANDLER["target_handler: Process I2C events"] CONTROLLER_OPS["Controller operations: read/write/etc"] end EMBEDDED_HAL --> STATE TRANSACTIONS --> STATE WRITE_ITER --> STATE STATE --> TARGET_HANDLER STATE --> CONTROLLER_OPS ``` -------------------------------- ### Configure Always-On Timer (AOT) with Powman Source: https://deepwiki.com/rp-rs/rp-hal/7-rom-functions-and-hardware-specific-features Creates a new POWMAN driver and configures the Always-On Timer (AOT) to use the crystal oscillator (XOSC) as the clock source. Starts the timer, sets an alarm 5 seconds in the future, and enables the alarm interrupt. The `?` operator propagates errors from `aot_set_clock`. The AOT continues running even when the core is powered down. ```rust // Create a new power management driver let mut powman = Powman::new(pac.POWMAN, None); // Set clock source to crystal oscillator let clock_source = AotClockSource::Xosc(FractionalFrequency::from_hz(12_000_000)); powman.aot_set_clock(clock_source)?; // Start the timer and set an alarm powman.aot_start(); let current_time = powman.aot_get_time(); powman.aot_set_alarm(current_time + 5_000_000); // 5 seconds powman.aot_alarm_enable(); powman.aot_alarm_interrupt_enable(); ``` -------------------------------- ### Single Buffer Memory to Memory Transfer Source: https://deepwiki.com/rp-rs/rp-hal/5.2-dma-system Configures a single buffer DMA transfer for memory-to-memory data movement. Uses `hal::dma::single_buffer::Config::new` with a channel, source buffer, and destination buffer. The transfer is started and waited on, returning the channel and buffers. ```rust // Memory to Memory transfer example let rx_buffer = [0u8; 10]; let tx_buffer = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let transfer = hal::dma::single_buffer::Config::new(dma.ch0, tx_buffer, rx_buffer); let started = transfer.start(); let (ch0, tx_buffer, rx_buffer) = started.wait(); ``` -------------------------------- ### Bidirectional SPI Transfer with Two Channels Source: https://deepwiki.com/rp-rs/rp-hal/5.2-dma-system Configures a bidirectional DMA transfer for SPI full-duplex communication. Uses `bidirectional::Config::new` with two channels, a transmit buffer, SPI peripheral, and receive buffer. The transfer is started and waited on, returning the channels, buffers, and SPI. ```rust // SPI bidirectional transfer example let rx_buf = [0u8; 10]; let tx_buf = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let transfer = bidirectional::Config::new((dma.ch0, dma.ch1), tx_buf, spi, rx_buf).start(); let ((ch0, ch1), tx_buf, spi, rx_buf) = transfer.wait(); ``` -------------------------------- ### Typical Initialization Pattern (Rust) Source: https://deepwiki.com/rp-rs/rp-hal/1-overview Rust code showing the typical initialization pattern: taking peripherals, setting up watchdog and clocks, and initializing GPIO pins. ```rust // Get access to the device peripherals let mut p = hal::pac::Peripherals::take().unwrap(); // Set up the watchdog and clocks let mut watchdog = hal::Watchdog::new(p.WATCHDOG); let clocks = hal::clocks::init_clocks_and_plls( XTAL_FREQ_HZ, p.XOSC, p.CLOCKS, p.PLL_SYS, p.PLL_USB, &mut p.RESETS, &mut watchdog, ).unwrap(); // Set up the GPIO pins let sio = hal::Sio::new(p.SIO); let pins = hal::gpio::Pins::new(p.IO_BANK0, p.PADS_BANK0, sio.gpio_bank0, &mut p.RESETS); ``` -------------------------------- ### Creating a Secure Boot Image with hal::block::ImageDef Source: https://deepwiki.com/rp-rs/rp-hal/7-rom-functions-and-hardware-specific-features Use this snippet to define a secure executable image and attach binary info metadata for picotool. It uses link sections and attributes to place the image definition and entries. ```rust // Create an image definition for a secure executable #[link_section = ".start_block"] #[used] pub static IMAGE_DEF: hal::block::ImageDef = hal::block::ImageDef::secure_exe(); // Add binary info metadata for the picotool #[link_section = ".bi_entries"] #[used] pub static PICOTOOL_ENTRIES: [hal::binary_info::EntryAddr; 3] = [ hal::binary_info::rp_cargo_bin_name!(), hal::binary_info::rp_cargo_version!(), hal::binary_info::rp_program_description!(c"Secure application example"), ]; ``` -------------------------------- ### Picotool Method: picotool load -x program.elf Source: https://deepwiki.com/rp-rs/rp-hal/2-getting-started Use this command to load firmware onto the device using picotool. The ELF file must be renamed with a .elf extension. This method is for compatibility with the Raspberry Pi Pico SDK ecosystem. ```bash picotool load -x program.elf ``` -------------------------------- ### UF2 Bootloader Method: cargo run --release Source: https://deepwiki.com/rp-rs/rp-hal/2-getting-started Use this command to compile and flash code via the UF2 bootloader. The board must be in bootloader mode (hold BOOTSEL while connecting USB) and appear as a mass storage device. This is the recommended method for most users. ```bash cargo run --release ``` -------------------------------- ### Using Boot Information with hal::rom_data::sys_info_api::boot_info Source: https://deepwiki.com/rp-rs/rp-hal/7-rom-functions-and-hardware-specific-features This snippet retrieves and prints boot information, including boot type, partition, and chained status. It matches boot type variants to human-readable strings. ```rust // Get information about how the device was booted if let Ok(Some(boot_info)) = hal::rom_data::sys_info_api::boot_info() { println!("Boot Type: {}", match boot_info.boot_type { BootType::Normal => "Normal", BootType::BootSel => "BOOTSEL button", BootType::RamImage => "RAM image", BootType::FlashUpdate => "Flash update", BootType::PcSp => "PC/SP specified", BootType::Unknown => "Unknown", }); println!("Partition: {}", boot_info.partition); println!("Chained: {}", boot_info.chained); } ``` -------------------------------- ### Build Command for I2C Loopback Test Source: https://deepwiki.com/rp-rs/rp-hal/6-development-and-testing Command to build the I2C loopback async test with the rp2040 feature enabled. Run from the on-target-tests directory. ```bash cd on-target-tests cargo build --test i2c_loopback_async --features rp2040 ``` -------------------------------- ### Initialize ADC with Adc::new Source: https://deepwiki.com/rp-rs/rp-hal/4.5-adc Creates an ADC instance using the ADC peripheral and RESETS peripheral. ```rust // Get the ADC peripheral let mut adc = Adc::new(peripherals.ADC, &mut peripherals.RESETS); ``` -------------------------------- ### .cargo/config.toml for RP2040 Build and Runner Source: https://deepwiki.com/rp-rs/rp-hal/2-getting-started Specifies the build target (thumbv6m-none-eabi) and linker flags for RP2040. Also configures the runner to use elf2uf2-rs for USB bootloader flashing, with an alternative probe-rs runner commented out. ```toml [build] target = "thumbv6m-none-eabi" # Default target for RP2040 [target.thumbv6m-none-eabi] rustflags = [ "-C", "link-arg=--nmagic", "-C", "link-arg=-Tlink.x", "-C", "link-arg=-Tdefmt.x", ] # For loading via USB bootloader runner = "elf2uf2-rs -d" # Alternatively, for loading via probe-rs # runner = "probe-rs run --chip RP2040" ``` -------------------------------- ### Initialize Clocks and PLLs (Rust) Source: https://deepwiki.com/rp-rs/rp-hal/3-core-hal-concepts Rust code to initialize clocks and PLLs using `hal::clocks::init_clocks_and_plls`. Configures XOSC, system PLL, USB PLL, and clock dividers. ```rust let clocks = hal::clocks::init_clocks_and_plls( XTAL_FREQ_HZ, p.XOSC, p.CLOCKS, p.PLL_SYS, p.PLL_USB, &mut p.RESETS, &mut watchdog, ).unwrap(); ``` -------------------------------- ### Add RP2040 target (thumbv6m-none-eabi) Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Adds the compile target for RP2040 (Raspberry Pi Pico) microcontrollers. ```bash rustup target add thumbv6m-none-eabi ``` -------------------------------- ### memory.x Linker Script for RP2040 Source: https://deepwiki.com/rp-rs/rp-hal/2-getting-started Defines the memory regions for the RP2040 linker script, including BOOT2, FLASH, and RAM. The exact layout may vary by microcontroller model. ```linker-script MEMORY { BOOT2 : ORIGIN = 0x10000000, LENGTH = 0x100 FLASH : ORIGIN = 0x10000100, LENGTH = 2048K - 0x100 RAM : ORIGIN = 0x20000000, LENGTH = 256K } ``` -------------------------------- ### Configure build target for RP2040/RP235x in .cargo/config.toml Source: https://deepwiki.com/rp-rs/rp-hal/2.2-programming-workflows Sets the Rust compilation target for RP2040 (thumbv6m-none-eabi) or RP235x in ARM mode (thumbv8m.main-none-eabihf). The commented alternative shows the RP235x option; RISC-V mode (riscv32imac-unknown-none-elf) is mentioned in the surrounding text but not shown here. ```toml [build] target = "thumbv6m-none-eabi" # For RP2040 # OR for RP235x: target = "thumbv8m.main-none-eabihf" # ARM mode ``` -------------------------------- ### Development workflow targets diagram Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Mermaid diagram showing the development and flashing workflow, including the Rust application code, BSP, HAL, build configuration, and flashing methods. ```mermaid flowchart LR subgraph "Development" CODE["Rust Application Code"] BSP["Board Support Package"] HAL["RP2040/RP235x HAL"] end subgraph "Building" CARGO["cargo build --target=TARGET"] CONFIG[".cargo/config.toml"] MEMORY["memory.x"] end subgraph "Flashing Methods" UF2["UF2 Bootloader (elf2uf2-rs)"] PROBE["Debug Probe (probe-rs)"] PICO["Command Line (picotool)"] end CODE --> BSP BSP --> HAL CODE --> CARGO CONFIG --> CARGO MEMORY --> CARGO CARGO --> ELF["ELF Binary"] ELF --> UF2CONVERT["elf2uf2-rs"] UF2CONVERT --> UF2FILE["UF2 File"] UF2FILE --> UF2 ELF --> PROBE ELF --> PICO UF2 --> DEVICE["Raspberry Silicon Device"] PROBE --> DEVICE PICO --> DEVICE ``` -------------------------------- ### Project Structure Diagram (Mermaid) Source: https://deepwiki.com/rp-rs/rp-hal/2-getting-started Shows the typical directory layout for an RP2040/RP235x embedded Rust project, including src/main.rs, Cargo.toml, .cargo/config.toml, and memory.x. ```mermaid graph TD subgraph "Project Structure" ROOT["Project Root"] SRC["src/"] MAIN["src/main.rs"] CARGO["Cargo.toml"] CONFIG[".cargo/config.toml"] MEMORY["memory.x"] ROOT --> SRC ROOT --> CARGO ROOT --> CONFIG ROOT --> MEMORY SRC --> MAIN end ``` -------------------------------- ### Initialize DMA Channels Statically Source: https://deepwiki.com/rp-rs/rp-hal/5.2-dma-system Splits the DMA peripheral into statically-typed channels, providing compile-time safety with unique types for each channel. ```rust // Initialize DMA channels statically let dma = pac.DMA.split(&mut pac.RESETS); ``` -------------------------------- ### Add RP235x ARM target (thumbv8m.main-none-eabihf) Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Adds the compile target for RP235x microcontrollers in ARM mode. ```bash rustup target add thumbv8m.main-none-eabihf ``` -------------------------------- ### Cargo.toml Dependencies for RP2040 Source: https://deepwiki.com/rp-rs/rp-hal/2-getting-started Defines the required HAL and support crates for an RP2040 project, including rp2040-hal, cortex-m, cortex-m-rt, embedded-hal, defmt, panic-halt, and rp2040-boot2. The [features] section enables default features like critical-section-impl, rt, and defmt. ```toml # For RP2040 projects (e.g., Raspberry Pi Pico) [dependencies] rp2040-hal = "0.11.0" cortex-m = "0.7.2" cortex-m-rt = "0.7" embedded-hal = "1.0.0" defmt = { version = "0.3", optional = true } panic-halt = "0.2.0" # Required for boot sequence rp2040-boot2 = "0.3.0" # Optional but useful features for rp2040-hal [features] default = ["critical-section-impl", "rt", "defmt"] ``` -------------------------------- ### Initialize DMA Channels Dynamically Source: https://deepwiki.com/rp-rs/rp-hal/5.2-dma-system Splits the DMA peripheral into dynamically-allocated channels, offering runtime flexibility through a common interface. ```rust // Initialize DMA channels dynamically let dma = pac.DMA.dyn_split(&mut pac.RESETS); ``` -------------------------------- ### Taking a Peripheral with Peripherals::take() Source: https://deepwiki.com/rp-rs/rp-hal/3-core-hal-concepts Use this to obtain exclusive ownership of a peripheral. The `Peripherals::take()` method returns an `Option`, so `unwrap()` is used to panic if the peripheral is already taken. This ensures only one part of the code can access the peripheral at a time. ```rust let mut p = hal::pac::Peripherals::take().unwrap(); ``` -------------------------------- ### Define ImageDef for Secure ARM Executable Source: https://deepwiki.com/rp-rs/rp-hal/7-rom-functions-and-hardware-specific-features Defines a static ImageDef block in the .start_block section using the secure_exe() constructor. This block is used by the boot ROM to boot a secure ARM executable. ```rust // Define an image definition block for a secure ARM executable #[link_section = ".start_block"] #[used] pub static IMAGE_DEF: hal::block::ImageDef = hal::block::ImageDef::secure_exe(); ``` -------------------------------- ### Repository structure diagram (Mermaid) Source: https://deepwiki.com/rp-rs/rp-hal/1-overview Mermaid diagram showing the relationships between core HAL crates and example/test crates. Use to understand the project's architecture and dependencies. ```mermaid graph TD subgraph "Core HAL Components" RP2040HAL["rp2040-hal"] RP235XHAL["rp235x-hal"] COMMON["rp-hal-common"] BINARY["rp-binary-info"] end subgraph "Examples and Tests" RP2040EXAMPLES["rp2040-hal-examples"] RP235XEXAMPLES["rp235x-hal-examples"] TESTS["on-target-tests"] end COMMON --> RP2040HAL COMMON --> RP235XHAL BINARY --> RP2040HAL BINARY --> RP235XHAL RP2040HAL --> RP2040EXAMPLES RP235XHAL --> RP235XEXAMPLES RP2040HAL --> TESTS RP235XHAL --> TESTS style RP2040HAL fill:#ddd,stroke:#333,stroke-width:2px style RP235XHAL fill:#ddd,stroke:#333,stroke-width:2px ``` -------------------------------- ### Add RP235x RISC-V target (riscv32imac-unknown-none-elf) Source: https://deepwiki.com/rp-rs/rp-hal/2.1-installation Adds the compile target for RP235x microcontrollers in RISC-V mode. ```bash rustup target add riscv32imac-unknown-none-elf ``` -------------------------------- ### Query Partition Table Information Source: https://deepwiki.com/rp-rs/rp-hal/7-rom-functions-and-hardware-specific-features Calls hal::rom_data::get_partition_table_info to retrieve partition table data into a buffer. The result is processed to extract the partition count and a flag indicating the presence of a partition table. ```rust // Get partition table information let mut buffer = [0u32; 16]; let result = unsafe { hal::rom_data::get_partition_table_info(buffer.as_mut_ptr(), buffer.len(), 0x0001) }; // Process partition information let partition_count = buffer[1] & 0xFF; let has_partition_table = (buffer[1] & (1 << 8)) != 0; ``` -------------------------------- ### Round-Robin ADC Sampling with FIFO Source: https://deepwiki.com/rp-rs/rp-hal/4.5-adc Samples multiple channels in sequence using round-robin mode. Requires previously configured ADC pins and a temperature sensor. ```rust let mut fifo = adc .build_fifo() .round_robin((&mut adc_pin_0, &mut adc_pin_1, &mut temp_sensor)) .start(); ``` -------------------------------- ### Creating a Timer with Automatic Reset Source: https://deepwiki.com/rp-rs/rp-hal/3-core-hal-concepts Creating a timer with `hal::Timer::new` automatically resets the timer peripheral. The `&mut p.RESETS` argument provides access to the reset controller, ensuring the timer is in a known state before use. ```rust // Creating a timer automatically resets the timer peripheral let timer = hal::Timer::new(p.TIMER, &mut p.RESETS); ``` -------------------------------- ### DMA Channel Architecture Diagram Source: https://deepwiki.com/rp-rs/rp-hal/5.2-dma-system Mermaid diagram illustrating the DMA hardware channels and HAL abstractions, including the DMAExt trait, Channels and DynChannels structs, and the single_buffer and bidirectional configurations. ```mermaid graph LR subgraph "DMA Hardware" DMA_HW["DMA Hardware"] CH0["Channel 0"] CH1["Channel 1"] CH2["Channel 2"] CHN["Channel N"] end subgraph "HAL Abstractions" DMAExt["DMAExt Trait"] CHANNELS["Channels struct"] DYN_CHANNELS["DynChannels struct"] SINGLE_BUFFER["single_buffer::Config"] BIDIRECTIONAL["bidirectional::Config"] READ_TARGET["ReadTarget trait"] WRITE_TARGET["WriteTarget trait"] end DMA_HW --- DMAExt DMAExt --> CHANNELS DMAExt --> DYN_CHANNELS CHANNELS --> CH0 CHANNELS --> CH1 CHANNELS --> CH2 CHANNELS --> CHN READ_TARGET --> SINGLE_BUFFER WRITE_TARGET --> SINGLE_BUFFER READ_TARGET --> BIDIRECTIONAL WRITE_TARGET --> BIDIRECTIONAL ```