From 5a8d5a8de5efae5c8e81f9cc832db187882f9acb Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 23 Feb 2026 18:15:14 +0800 Subject: [PATCH 01/10] fix allocation bug for ifram --- services/bao1x-hal-service/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/bao1x-hal-service/src/main.rs b/services/bao1x-hal-service/src/main.rs index d612e0e25..50d119b08 100644 --- a/services/bao1x-hal-service/src/main.rs +++ b/services/bao1x-hal-service/src/main.rs @@ -96,10 +96,10 @@ fn try_alloc(ifram_allocs: &mut Vec>, size: usize, sender: Sender } else { if free_start.is_some() { log::trace!("Adding unallocated page at {} to length", index); - found_len += 1; if found_len >= size_pages { break; } + found_len += 1; } else { log::trace!("Starting allocation search at {}", index); free_start = Some(index); From bd2a69327b7c602d7f8beff6cd989e64a8a8b88c Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 23 Feb 2026 18:15:38 +0800 Subject: [PATCH 02/10] add working draft of ADC driver this is based on a reference driver in C but translated largely by Claude and then checked & signed off by me. --- libs/bao1x-hal/src/udma/adc.rs | 450 +++++++++++++++++++++++++++++++++ libs/bao1x-hal/src/udma/mod.rs | 2 + 2 files changed, 452 insertions(+) create mode 100644 libs/bao1x-hal/src/udma/adc.rs diff --git a/libs/bao1x-hal/src/udma/adc.rs b/libs/bao1x-hal/src/udma/adc.rs new file mode 100644 index 000000000..1c44ae5b2 --- /dev/null +++ b/libs/bao1x-hal/src/udma/adc.rs @@ -0,0 +1,450 @@ +//! UDMA ADC block driver +//! +//! Supports internal temperature sensor and external voltage measurement on +//! PA04–PA07 via the uDMA RX channel. +//! +//! # `std` (Xous userspace) +//! ```no_run +//! let mut adc = unsafe { Adc::new(perclk_freq) }; +//! let raw = adc.read_raw(AdcSource::Temperature); +//! let temp_c = Adc::raw_to_temp_celsius(raw as f64); +//! +//! let raw = adc.read_raw(AdcSource::Ext(AdcExtChannel::Pa04)); +//! let volts = Adc::raw_to_voltage(raw); +//! ``` +//! +//! # `no_std` (loader / bare-metal) +//! ```no_run +//! let mut adc = unsafe { Adc::new_baremetal(perclk_freq, dma_buf_phys) }; // no_std +//! ``` + +use utralib::utra::udma_adc; +use utralib::*; + +use crate::ifram::IframRange; +use crate::udma::*; + +// ============================================================================ +// Fine-grained field definitions for REG_CR_ADC +// +// The auto-generated UTRA only exposes one monolithic 28-bit field +// (REG_CR_ADC_CR_ADC). We break it out here to match the datasheet's +// per-bit definitions for ADC_CR_CFG (byte offset 0x10, word offset 4). +// ============================================================================ +pub mod cr_adc { + use super::*; + + /// Bit[0]: Bandgap chopper enable (0 = disable, 1 = enable) + pub const CHOPPER_EN: Field = Field::new(1, 0, udma_adc::REG_CR_ADC); + /// Bit[1]: Temperature-related voltage buffer (0 = disable, 1 = enable) + pub const TEMP_BUF_EN: Field = Field::new(1, 1, udma_adc::REG_CR_ADC); + /// Bit[2]: Bandgap voltage buffer / reference select + /// 0 = disable buffer, use AVDD as reference + /// 1 = enable buffer, use bandgap voltage as reference + pub const BANDGAP_BUF_EN: Field = Field::new(1, 2, udma_adc::REG_CR_ADC); + /// Bit[3]: External voltage buffer (0 = disable, 1 = enable) + pub const EXT_BUF_EN: Field = Field::new(1, 3, udma_adc::REG_CR_ADC); + /// Bit[4]: Temperature-related voltage control (0 = voltage 1, 1 = voltage 2) + pub const TEMP_V_CTRL: Field = Field::new(1, 4, udma_adc::REG_CR_ADC); + /// Bit[5]: Temperature voltage filter bypass (0 = filter, 1 = bypass) + pub const TEMP_FILTER_BYPASS: Field = Field::new(1, 5, udma_adc::REG_CR_ADC); + /// Bit[6]: Bandgap voltage filter bypass (0 = filter, 1 = bypass) + pub const BANDGAP_FILTER_BYPASS: Field = Field::new(1, 6, udma_adc::REG_CR_ADC); + /// Bits[12:8]: ADC clock cycles per conversion (must be ≥ 14) + pub const DATA_COUNT: Field = Field::new(5, 8, udma_adc::REG_CR_ADC); + /// Bit[13]: Bandgap / temperature sensor enable + pub const SENSOR_EN: Field = Field::new(1, 13, udma_adc::REG_CR_ADC); + /// Bit[14]: ADC enable + pub const ADC_EN: Field = Field::new(1, 14, udma_adc::REG_CR_ADC); + /// Bit[15]: ADC reset (write 1 to reset) + pub const ADC_RST: Field = Field::new(1, 15, udma_adc::REG_CR_ADC); + /// Bits[23:16]: Clock frequency divider. + /// adc_clk = perclk / (2 × FD). The resulting adc_clk must be 0.2–1.6 MHz. + pub const CLK_FD: Field = Field::new(8, 16, udma_adc::REG_CR_ADC); + /// Bits[25:24]: ADC input mux + /// 00 = temperature-related voltage (internal) + /// 01 = external voltage + pub const ADC_SEL: Field = Field::new(2, 24, udma_adc::REG_CR_ADC); + /// Bits[27:26]: External analog input select + /// 00 = PA04 (ADC0), 01 = PA05 (ADC1), + /// 10 = PA06 (ADC2), 11 = PA07 (ADC3) + pub const VIN_SEL: Field = Field::new(2, 26, udma_adc::REG_CR_ADC); +} + +// ============================================================================ +// Public types +// ============================================================================ + +/// External analog input channel (PA04–PA07). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(usize)] +pub enum AdcExtChannel { + /// PA04 / ADC0 + Pa04 = 0, + /// PA05 / ADC1 + Pa05 = 1, + /// PA06 / ADC2 + Pa06 = 2, + /// PA07 / ADC3 + Pa07 = 3, +} + +/// ADC measurement source. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AdcSource { + /// Internal temperature sensor + Temperature, + /// External voltage on the specified channel + Ext(AdcExtChannel), +} + +/// Target ADC conversion clock in kHz. The divider is computed from `perclk` +/// so that adc_clk lands as close to this as possible within the valid +/// 200–1600 kHz range. +const ADC_TARGET_CLK_KHZ: u32 = 1_000; + +/// Minimum clock cycles per conversion (from the datasheet). +const ADC_MIN_DATA_COUNT: u32 = 14; + +/// The ADC is RX-only; the entire IFRAM page is the receive buffer. +const ADC_RX_BUF_SIZE: usize = 4096; + +// ============================================================================ +// Driver +// ============================================================================ + +/// UDMA ADC block driver. +pub struct Adc { + csr: CSR, + /// IFRAM allocation backing the uDMA RX buffer. + #[allow(dead_code)] + ifram: IframRange, + /// Current peripheral clock frequency in Hz, used to compute the ADC + /// clock divider. Updated via [`update_perclk`]. + perclk_freq: u32, +} + +/// Blanket [`Udma`] trait implementation so the generic uDMA helpers +/// (`udma_busy`, `udma_enqueue`, etc.) work on `Adc`. +impl Udma for Adc { + fn csr_mut(&mut self) -> &mut CSR { &mut self.csr } + + fn csr(&self) -> &CSR { &self.csr } +} + +impl Adc { + // --- Construction -------------------------------------------------------- + + /// Create a new ADC driver, mapping the hardware registers and allocating + /// an IFRAM DMA buffer. + /// + /// `perclk_freq` is the UDMA peripheral clock frequency in Hz (derived + /// from the system clock and the `fdper` fractional divider). + /// + /// # Safety + /// + /// Caller must ensure the global UDMA state has been initialized (clocks + /// un-gated, events configured) before calling this, and must manually + /// gate the ADC clock again when the driver is no longer needed. + #[cfg(feature = "std")] + pub unsafe fn new(perclk_freq: u32) -> Self { + let adc_mem = xous::syscall::map_memory( + xous::MemoryAddress::new(udma_adc::HW_UDMA_ADC_BASE), + None, + 4096, + xous::MemoryFlags::R | xous::MemoryFlags::W, + ) + .expect("couldn't map ADC registers"); + + let csr = CSR::new(adc_mem.as_mut_ptr() as *mut u32); + let ifram = IframRange::request(ADC_RX_BUF_SIZE, None).expect("couldn't allocate IFRAM for ADC"); + + let mut adc = Adc { csr, ifram, perclk_freq }; + adc.init(); + adc + } + + /// Create a bare-metal ADC driver (no MMU, physical addresses used + /// directly). + /// + /// # Safety + /// + /// Same preconditions as [`new`], plus the caller is responsible for + /// ensuring `udma_buf_phys` points to a valid, word-aligned DMA buffer + /// region of at least [`ADC_RX_BUF_SIZE`] bytes that is accessible to the + /// uDMA engine. + #[cfg(not(feature = "std"))] + pub unsafe fn new_baremetal(perclk_freq: u32, udma_buf_phys: usize) -> Self { + let csr = CSR::new(udma_adc::HW_UDMA_ADC_BASE as *mut u32); + let ifram = IframRange::from_raw_parts( + udma_buf_phys, + udma_buf_phys, // virt == phys in bare-metal + ADC_RX_BUF_SIZE, + ); + + let mut adc = Adc { csr, ifram, perclk_freq }; + adc.init(); + adc + } + + /// Re-acquire a handle to a previously initialized ADC. + /// + /// This is the equivalent of the UART's `get_handle` — use it when the + /// hardware was already configured (e.g. by the loader) and you just need + /// a driver object to operate on it. + /// + /// # Safety + /// + /// Only safe when the ADC hardware is already initialized and the + /// provided addresses are valid. + pub unsafe fn get_handle( + csr_virt_addr: usize, + udma_phys_addr: usize, + udma_virt_addr: usize, + perclk_freq: u32, + ) -> Self { + let csr = CSR::new(csr_virt_addr as *mut u32); + let ifram = IframRange::from_raw_parts(udma_phys_addr, udma_virt_addr, ADC_RX_BUF_SIZE); + Adc { csr, ifram, perclk_freq } + } + + // --- Clock management --------------------------------------------------- + + /// Compute the clock frequency divider for a given peripheral clock. + /// + /// `perclk_khz`: peripheral clock in kHz. + /// `target_khz`: desired ADC clock in kHz (clamped to 200–1600). + /// + /// The hardware divides: adc_clk = perclk / (2 × FD). + fn calc_clk_fd(perclk_khz: u32, target_khz: u32) -> u32 { + let target_khz = target_khz.clamp(200, 1600); + let fd = perclk_khz / (2 * target_khz); + fd.clamp(1, 0xFF) + } + + /// Notify the driver that the peripheral clock frequency has changed + /// (e.g. after a power-mode transition). Re-computes and writes the + /// ADC clock divider. + /// + /// `perclk_freq`: new peripheral clock in **Hz**. + pub fn update_perclk(&mut self, perclk_freq: u32) { + self.perclk_freq = perclk_freq; + + let fd = Self::calc_clk_fd(perclk_freq / 1_000, ADC_TARGET_CLK_KHZ); + + // Read-modify-write: touch only CLK_FD[23:16] + let mut cr = self.csr.r(udma_adc::REG_CR_ADC); + cr &= !((cr_adc::CLK_FD.mask() as u32) << cr_adc::CLK_FD.offset()); + cr |= fd << cr_adc::CLK_FD.offset(); + self.csr.wo(udma_adc::REG_CR_ADC, cr); + } + + // --- Delays ------------------------------------------------------------- + + #[cfg(feature = "std")] + fn delay_us(us: u64) { std::thread::sleep(std::time::Duration::from_micros(us)); } + + /// Bare-metal delay stub. + #[cfg(not(feature = "std"))] + fn delay_us(us: u64) { + // abuse the d11ctime timer to create some time-out like thing + let mut d11c = CSR::new(utra::d11ctime::HW_D11CTIME_BASE as *mut u32); + d11c.wfo(utra::d11ctime::CONTROL_COUNT, 333); // 1.0us per interval + let mut polarity = d11c.rf(utra::d11ctime::HEARTBEAT_BEAT); + for _ in 0..us { + while polarity == d11c.rf(utra::d11ctime::HEARTBEAT_BEAT) {} + polarity = d11c.rf(utra::d11ctime::HEARTBEAT_BEAT); + } + // we have to split this because we don't know where we caught the previous interval + if us == 1 { + while polarity == d11c.rf(utra::d11ctime::HEARTBEAT_BEAT) {} + } + } + + // --- Initialization ----------------------------------------------------- + + /// Full ADC power-on sequence per the datasheet start timing spec: + /// + /// 1. Stop any in-flight DMA + /// 2. Assert reset, set clock divider + data count + sensor enable + /// 3. Wait ≥ 10 µs (t1) + /// 4. Enable bandgap reference + voltage buffers + /// 5. Wait (t2 — spec says 0 µs min, we add margin) + /// 6. Enable ADC + /// 7. Wait ≥ 90 µs (t3) + /// + /// Defaults to temperature sensor source after init. + fn init(&mut self) { + // Step 0 — stop any prior DMA + let rx_cfg = self.csr.r(udma_adc::REG_RX_CFG); + if (rx_cfg & ((1 << 4) | (1 << 5))) != 0 { + self.csr.rmwf(udma_adc::REG_RX_CFG_R_RX_CLR, 1); + } + + // Step 1 — reset + base config + self.csr.wo(udma_adc::REG_CR_ADC, 0); + + let fd = Self::calc_clk_fd(self.perclk_freq / 1_000, ADC_TARGET_CLK_KHZ); + + let mut cr: u32 = 0; + cr |= 1 << cr_adc::ADC_RST.offset(); + cr |= fd << cr_adc::CLK_FD.offset(); + cr |= ADC_MIN_DATA_COUNT << cr_adc::DATA_COUNT.offset(); + cr |= 1 << cr_adc::SENSOR_EN.offset(); + self.csr.wo(udma_adc::REG_CR_ADC, cr); + + // Step 2 — t1 + Self::delay_us(20); + + // Step 3 — bandgap + temperature buffers + cr |= 1 << cr_adc::BANDGAP_BUF_EN.offset(); + cr |= 1 << cr_adc::TEMP_BUF_EN.offset(); + cr |= 1 << cr_adc::TEMP_FILTER_BYPASS.offset(); + cr |= 1 << cr_adc::BANDGAP_FILTER_BYPASS.offset(); + self.csr.wo(udma_adc::REG_CR_ADC, cr); + + // Step 4 — t2 + Self::delay_us(20); + + // Step 5 — enable ADC + cr |= 1 << cr_adc::ADC_EN.offset(); + self.csr.wo(udma_adc::REG_CR_ADC, cr); + + // Step 6 — t3 + Self::delay_us(120); + } + + // --- Source selection ---------------------------------------------------- + + /// Reconfigure the analog mux for the given source. + /// + /// Read-modify-writes only the buffer-enable and mux-select bits. + pub fn configure_source(&mut self, source: AdcSource) { + let mut cr = self.csr.r(udma_adc::REG_CR_ADC); + + // Clear mux-related bits in one shot + cr &= !((1u32 << cr_adc::TEMP_BUF_EN.offset()) + | (1u32 << cr_adc::EXT_BUF_EN.offset()) + | ((cr_adc::ADC_SEL.mask() as u32) << cr_adc::ADC_SEL.offset()) + | ((cr_adc::VIN_SEL.mask() as u32) << cr_adc::VIN_SEL.offset())); + + match source { + AdcSource::Temperature => { + cr |= 1 << cr_adc::TEMP_BUF_EN.offset(); + // ADC_SEL = 00 (temperature), VIN_SEL = don't-care + } + AdcSource::Ext(ch) => { + cr |= 1 << cr_adc::EXT_BUF_EN.offset(); + cr |= 1 << cr_adc::ADC_SEL.offset(); // 01 = external + cr |= (ch as u32) << cr_adc::VIN_SEL.offset(); + } + } + + self.csr.wo(udma_adc::REG_CR_ADC, cr); + Self::delay_us(20); + } + + // --- Measurement -------------------------------------------------------- + + /// Blocking single-shot read. Returns the raw 10-bit result (0–1023). + pub fn read_raw(&mut self, source: AdcSource) -> u16 { + self.configure_source(source); + + self.csr.rmwf(udma_adc::REG_RX_CFG_R_RX_CLR, 1); + + // Enqueue a 1-word (4-byte) DMA transfer + #[cfg(feature = "std")] + unsafe { + self.udma_enqueue(Bank::Rx, &self.ifram.as_phys_slice::()[..4], CFG_EN | CFG_SIZE_32); + } + #[cfg(not(feature = "std"))] + unsafe { + self.udma_enqueue(Bank::Rx, &self.ifram.as_phys_slice::()[..4], CFG_EN | CFG_SIZE_32); + } + + while self.udma_busy(Bank::Rx) { + #[cfg(feature = "std")] + xous::yield_slice(); + } + + #[cfg(any(feature = "std", feature = "kernel"))] + let val = self.ifram.as_slice::()[0]; + #[cfg(not(any(feature = "std", feature = "kernel")))] + let val = unsafe { self.ifram.as_phys_slice::()[0] }; + + (val & 0x3FF) as u16 + } + + /// Read `n` samples and return the average (raw 10-bit value). + pub fn read_raw_averaged(&mut self, source: AdcSource, n: usize) -> u16 { + let max_words = ADC_RX_BUF_SIZE / core::mem::size_of::(); + assert!(n > 0 && n <= max_words, "n must be 1..={}", max_words); + + self.configure_source(source); + + self.csr.rmwf(udma_adc::REG_RX_CFG_R_RX_CLR, 1); + + let byte_len = n * core::mem::size_of::(); + #[cfg(feature = "std")] + unsafe { + self.udma_enqueue(Bank::Rx, &self.ifram.as_phys_slice::()[..byte_len], CFG_EN | CFG_SIZE_32); + } + #[cfg(not(feature = "std"))] + unsafe { + self.udma_enqueue(Bank::Rx, &self.ifram.as_phys_slice::()[..byte_len], CFG_EN | CFG_SIZE_32); + } + + while self.udma_busy(Bank::Rx) { + #[cfg(feature = "std")] + xous::yield_slice(); + } + + let mut sum: u32 = 0; + for i in 0..n { + #[cfg(any(feature = "std", feature = "kernel"))] + let val = self.ifram.as_slice::()[i]; + #[cfg(not(any(feature = "std", feature = "kernel")))] + let val = unsafe { self.ifram.as_phys_slice::()[i] }; + + sum += val & 0x3FF; + } + (sum / n as u32) as u16 + } + + /// Arm continuous DMA conversion. The uDMA will repeatedly fill the + /// buffer and wrap. Use the ADC RX interrupt (IRQn 121 - irqarray8::EV_PENDING_ADC_RX) or poll + /// `udma_busy(Bank::Rx)` to track progress. + pub fn start_continuous(&mut self, source: AdcSource) { + self.configure_source(source); + + self.csr.rmwf(udma_adc::REG_RX_CFG_R_RX_CLR, 1); + + #[cfg(feature = "std")] + unsafe { + self.udma_enqueue(Bank::Rx, self.ifram.as_phys_slice::(), CFG_EN | CFG_SIZE_32 | CFG_CONT); + } + #[cfg(not(feature = "std"))] + unsafe { + self.udma_enqueue(Bank::Rx, self.ifram.as_phys_slice::(), CFG_EN | CFG_SIZE_32 | CFG_CONT); + } + } + + /// Stop continuous conversion. + pub fn stop_continuous(&mut self) { self.csr.rmwf(udma_adc::REG_RX_CFG_R_RX_CLR, 1); } + + // --- Conversion helpers ------------------------------------------------- + + /// Raw → temperature in °C (float). + /// + /// Linear regression on the datasheet table + /// T = −0.5877 × raw + 328.68, R² ≈ 0.99997 + pub fn raw_to_temp_celsius(raw: u16) -> f32 { -0.587_744_8 * raw as f32 + 328.679_84 } + + /// Raw → temperature in tenths of °C (integer). + /// e.g. 253 means 25.3 °C. + pub fn raw_to_temp_tenths_c(raw: u16) -> i16 { 3287i16 - (raw as i32 * 587_745 / 100_000) as i16 } + + /// Raw → voltage in volts (bandgap ref, Vbg = 1.208 V). + /// V_in = raw / 1023 × 1.208 + pub fn raw_to_voltage(raw: u16) -> f32 { (raw as f32 / 1023.0) * 1.208 } +} diff --git a/libs/bao1x-hal/src/udma/mod.rs b/libs/bao1x-hal/src/udma/mod.rs index bf2064959..593bb40e4 100644 --- a/libs/bao1x-hal/src/udma/mod.rs +++ b/libs/bao1x-hal/src/udma/mod.rs @@ -1,9 +1,11 @@ +pub mod adc; pub mod i2c; pub mod spim; pub mod uart; use core::mem::size_of; +pub use adc::*; use bao1x_api::*; pub use i2c::*; pub use spim::*; From ac1e451aa1365d8aa1608861b28a2b3b8576fdf3 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 23 Feb 2026 18:52:23 +0800 Subject: [PATCH 03/10] add routines for setting/updating i2c clocks in anticipation for frequency scaling support --- libs/bao1x-hal/src/udma/i2c.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/libs/bao1x-hal/src/udma/i2c.rs b/libs/bao1x-hal/src/udma/i2c.rs index 4092adcd4..8ab0fa830 100644 --- a/libs/bao1x-hal/src/udma/i2c.rs +++ b/libs/bao1x-hal/src/udma/i2c.rs @@ -75,7 +75,10 @@ pub struct I2cDriver<'a> { #[allow(dead_code)] // used in bao1x channel: I2cChannel, divider: u16, + // cached value of perclk perclk_freq: u32, + // cached value of our clock setting + i2c_freq: u32, pub ifram: IframRange, tx_buf: &'static mut [u8], tx_buf_phys: &'static mut [u8], @@ -197,6 +200,7 @@ impl<'a> I2cDriver<'a> { seq_len: 0, pending: I2cPending::Idle, perclk_freq, + i2c_freq, }; i2c.send_cmd_list(&[I2cCmd::Config(divider)]); i2c @@ -205,6 +209,12 @@ impl<'a> I2cDriver<'a> { pub fn set_freq(&mut self, freq_hz: u32) { // divide-by-4 is an empirical observation self.divider = ((self.perclk_freq / (freq_hz * 4)).min(u16::MAX as u32)) as u16; + self.i2c_freq = freq_hz; + } + + pub fn update_perclk(&mut self, perclk_freq: u32) { + self.perclk_freq = perclk_freq; + self.set_freq(self.i2c_freq); } // always blocks From 35168f80857ac7afe06c8269636f64b14d241898 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 23 Feb 2026 18:52:55 +0800 Subject: [PATCH 04/10] add getters/setters for adc channel specifications --- libs/bao1x-hal/src/udma/adc.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/libs/bao1x-hal/src/udma/adc.rs b/libs/bao1x-hal/src/udma/adc.rs index 1c44ae5b2..2f79a4f98 100644 --- a/libs/bao1x-hal/src/udma/adc.rs +++ b/libs/bao1x-hal/src/udma/adc.rs @@ -98,6 +98,26 @@ pub enum AdcSource { Ext(AdcExtChannel), } +impl AdcSource { + pub fn to_usize(self) -> usize { + match self { + AdcSource::Temperature => 0, + AdcSource::Ext(ch) => 1 + ch as usize, // 1..=4 + } + } + + pub fn from_usize(val: usize) -> AdcSource { + match val { + 0 => AdcSource::Temperature, + 1 => AdcSource::Ext(AdcExtChannel::Pa04), + 2 => AdcSource::Ext(AdcExtChannel::Pa05), + 3 => AdcSource::Ext(AdcExtChannel::Pa06), + 4 => AdcSource::Ext(AdcExtChannel::Pa07), + _ => unimplemented!("AdcSource::from_usize: invalid value {}", val), + } + } +} + /// Target ADC conversion clock in kHz. The divider is computed from `perclk` /// so that adc_clk lands as close to this as possible within the valid /// 200–1600 kHz range. @@ -107,7 +127,7 @@ const ADC_TARGET_CLK_KHZ: u32 = 1_000; const ADC_MIN_DATA_COUNT: u32 = 14; /// The ADC is RX-only; the entire IFRAM page is the receive buffer. -const ADC_RX_BUF_SIZE: usize = 4096; +pub const ADC_RX_BUF_SIZE: usize = 4096; // ============================================================================ // Driver From 302b7b65bf7b5e4e218aabd8fdc9af74a5050a48 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 23 Feb 2026 18:53:19 +0800 Subject: [PATCH 05/10] add std opcodes for ADC operations --- libs/bao1x-api/src/api.rs | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/libs/bao1x-api/src/api.rs b/libs/bao1x-api/src/api.rs index 794964839..d3ea93384 100644 --- a/libs/bao1x-api/src/api.rs +++ b/libs/bao1x-api/src/api.rs @@ -40,6 +40,8 @@ pub enum HalOpcode { ConfigureUdmaEvent = 8, // blocking scalar UdmaIrqStatusBits = 16, + // blocking scalar + UpdatePerclk = 18, /// I2C operations I2c = 9, @@ -51,16 +53,10 @@ pub enum HalOpcode { ConfigureIoxIrq = 11, IrqLocalHandler = 12, + /// Adc operations + // blocking scalar + ReadAdcChannel = 32, + /// Manipulate the OS timer SetPreemptionState = 64, - - /// Behavior opcode base - #[cfg(feature = "bio")] - BehaviorBase0 = 0x1000, - #[cfg(feature = "bio")] - BehaviorBase1 = 0x2000, - #[cfg(feature = "bio")] - BehaviorBase2 = 0x3000, - #[cfg(feature = "bio")] - BehaviorBase3 = 0x4000, } From 18e72a970ccd02894c27e8afbde7ba19cd4aff79 Mon Sep 17 00:00:00 2001 From: bunnie Date: Mon, 23 Feb 2026 18:53:37 +0800 Subject: [PATCH 06/10] add draft ADC support to hal service --- services/bao1x-hal-service/src/lib.rs | 33 ++++++++++++++++++++++++++ services/bao1x-hal-service/src/main.rs | 27 ++++++++++++++++++++- 2 files changed, 59 insertions(+), 1 deletion(-) diff --git a/services/bao1x-hal-service/src/lib.rs b/services/bao1x-hal-service/src/lib.rs index baaa91b2e..e0c500fe5 100644 --- a/services/bao1x-hal-service/src/lib.rs +++ b/services/bao1x-hal-service/src/lib.rs @@ -2,6 +2,7 @@ pub mod api; pub mod trng; use bao1x_api::*; +use bao1x_hal::udma::AdcSource; use num_traits::*; use xous::{Message, send_message}; use xous_api_susres::api::Opcode as SusresOp; @@ -128,6 +129,38 @@ impl UdmaGlobalConfig for UdmaGlobal { } } +pub struct Adc { + conn: xous::CID, +} +impl Adc { + pub fn new() -> Self { + let xns = xous_names::XousNames::new().unwrap(); + let conn = + xns.request_connection(SERVER_NAME_BAO1X_HAL).expect("Couldn't connect to bao1x HAL server"); + Adc { conn } + } + + /// Averaging can range from 1..1024. Out of range values are silently converted to in-range values + /// based on saturating logic. None for averaging translates to 1. + pub fn read_raw(&self, channel: AdcSource, averaging: Option) -> u16 { + let averaging = + averaging.unwrap_or(1).min(1).max((bao1x_hal::udma::ADC_RX_BUF_SIZE / size_of::()) as u16); + match xous::send_message( + self.conn, + xous::Message::new_blocking_scalar( + HalOpcode::ReadAdcChannel.to_usize().unwrap(), + channel.to_usize(), + averaging as usize, + 0, + 0, + ), + ) { + Ok(xous::Result::Scalar5(_, value, _, _, _)) => value as u16, + _ => panic!("Unhandled response on Adc::read_raw"), + } + } +} + pub struct ClockManager { conn: xous::CID, } diff --git a/services/bao1x-hal-service/src/main.rs b/services/bao1x-hal-service/src/main.rs index 50d119b08..4d09ed973 100644 --- a/services/bao1x-hal-service/src/main.rs +++ b/services/bao1x-hal-service/src/main.rs @@ -4,7 +4,10 @@ mod servers; use std::pin::Pin; use bao1x_api::*; -use bao1x_hal::{iox::Iox, udma::GlobalConfig}; +use bao1x_hal::{ + iox::Iox, + udma::{AdcSource, GlobalConfig}, +}; use bitfield::*; use num_traits::*; use udma::UdmaGlobalConfig; @@ -278,6 +281,11 @@ fn main() { // The index of the array corresponds to the slot. let mut irq_table: [Option; 8] = [None; 8]; + // allocate the ADC + udma_global.clock_on(PeriphId::Adc); + // safety: clocks are turned on, and we can assume PERCLK is configured at boot + let mut adc = unsafe { bao1x_hal::udma::Adc::new(bao1x_api::PERCLK) }; + let mut msg_opt = None; log::debug!("Starting main loop"); loop { @@ -615,6 +623,23 @@ fn main() { os_timer.wfo(utra::timer0::EV_ENABLE_ZERO, if timer_run { 1 } else { 0 }); } } + HalOpcode::UpdatePerclk => { + if let Some(scalar) = msg_opt.as_mut().unwrap().body.scalar_message_mut() { + let new_perclk = scalar.arg1 as u32; + i2c.update_perclk(new_perclk); + adc.update_perclk(new_perclk); + } + } + HalOpcode::ReadAdcChannel => { + if let Some(scalar) = msg_opt.as_mut().unwrap().body.scalar_message_mut() { + let channel = AdcSource::from_usize(scalar.arg1); + // sets to at least 1, even if the arg is 0 + // max averaging is limited by the size of the ADC buffer + let averaging = + scalar.arg2.max(1).min(bao1x_hal::udma::ADC_RX_BUF_SIZE / size_of::()); + scalar.arg1 = adc.read_raw_averaged(channel, averaging) as usize; + } + } HalOpcode::InvalidCall => { log::error!("Invalid opcode received: {:?}", msg_opt); } From 663139b60787fa1b30548344cfda907b4a613270 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 24 Feb 2026 01:33:25 +0800 Subject: [PATCH 07/10] split ADC into its own service thread this allows the ADC to depend on core HAL services. It's structured so that other 'misc' services would go into the "other" module, just to keep the overhead of threads/services down a bit. Up until this point all the other services mapped to existing/other server names, like the RTC, susres, etc. --- services/bao1x-hal-service/src/lib.rs | 26 ++++- services/bao1x-hal-service/src/main.rs | 24 +---- services/bao1x-hal-service/src/servers.rs | 1 + .../bao1x-hal-service/src/servers/others.rs | 95 +++++++++++++++++++ 4 files changed, 123 insertions(+), 23 deletions(-) create mode 100644 services/bao1x-hal-service/src/servers/others.rs diff --git a/services/bao1x-hal-service/src/lib.rs b/services/bao1x-hal-service/src/lib.rs index e0c500fe5..b2e295531 100644 --- a/services/bao1x-hal-service/src/lib.rs +++ b/services/bao1x-hal-service/src/lib.rs @@ -2,7 +2,7 @@ pub mod api; pub mod trng; use bao1x_api::*; -use bao1x_hal::udma::AdcSource; +use bao1x_hal::udma::{AdcExtChannel, AdcSource}; use num_traits::*; use xous::{Message, send_message}; use xous_api_susres::api::Opcode as SusresOp; @@ -136,19 +136,22 @@ impl Adc { pub fn new() -> Self { let xns = xous_names::XousNames::new().unwrap(); let conn = - xns.request_connection(SERVER_NAME_BAO1X_HAL).expect("Couldn't connect to bao1x HAL server"); + xns.request_connection(SERVER_NAME_BAO1X_OTHERS).expect("Couldn't connect to bao1x HAL server"); Adc { conn } } /// Averaging can range from 1..1024. Out of range values are silently converted to in-range values /// based on saturating logic. None for averaging translates to 1. + /// + /// For analog channels, the measurement goes from 0..1.208v. There is some nonlinearity observed below + /// 0.2V, so the "sweet spot" is 0.2V-1.2V. pub fn read_raw(&self, channel: AdcSource, averaging: Option) -> u16 { let averaging = averaging.unwrap_or(1).min(1).max((bao1x_hal::udma::ADC_RX_BUF_SIZE / size_of::()) as u16); match xous::send_message( self.conn, xous::Message::new_blocking_scalar( - HalOpcode::ReadAdcChannel.to_usize().unwrap(), + PeripheralOpcode::ReadAdcChannel.to_usize().unwrap(), channel.to_usize(), averaging as usize, 0, @@ -159,6 +162,23 @@ impl Adc { _ => panic!("Unhandled response on Adc::read_raw"), } } + + /// Safety: this method does no checks for concurrent use of the analog channels. + /// It is up to the caller to ensure that ADC0-3 (mapped to PA4-7) have no conflicts + /// with other I/O functions. + pub unsafe fn enable_channel(&self, channel: AdcExtChannel) { + xous::send_message( + self.conn, + xous::Message::new_blocking_scalar( + PeripheralOpcode::EnableChannel.to_usize().unwrap(), + channel.into(), + 0, + 0, + 0, + ), + ) + .ok(); + } } pub struct ClockManager { diff --git a/services/bao1x-hal-service/src/main.rs b/services/bao1x-hal-service/src/main.rs index 4d09ed973..2b8eefd47 100644 --- a/services/bao1x-hal-service/src/main.rs +++ b/services/bao1x-hal-service/src/main.rs @@ -4,10 +4,7 @@ mod servers; use std::pin::Pin; use bao1x_api::*; -use bao1x_hal::{ - iox::Iox, - udma::{AdcSource, GlobalConfig}, -}; +use bao1x_hal::{iox::Iox, udma::GlobalConfig}; use bitfield::*; use num_traits::*; use udma::UdmaGlobalConfig; @@ -281,11 +278,6 @@ fn main() { // The index of the array corresponds to the slot. let mut irq_table: [Option; 8] = [None; 8]; - // allocate the ADC - udma_global.clock_on(PeriphId::Adc); - // safety: clocks are turned on, and we can assume PERCLK is configured at boot - let mut adc = unsafe { bao1x_hal::udma::Adc::new(bao1x_api::PERCLK) }; - let mut msg_opt = None; log::debug!("Starting main loop"); loop { @@ -627,17 +619,6 @@ fn main() { if let Some(scalar) = msg_opt.as_mut().unwrap().body.scalar_message_mut() { let new_perclk = scalar.arg1 as u32; i2c.update_perclk(new_perclk); - adc.update_perclk(new_perclk); - } - } - HalOpcode::ReadAdcChannel => { - if let Some(scalar) = msg_opt.as_mut().unwrap().body.scalar_message_mut() { - let channel = AdcSource::from_usize(scalar.arg1); - // sets to at least 1, even if the arg is 0 - // max averaging is limited by the size of the ADC buffer - let averaging = - scalar.arg2.max(1).min(bao1x_hal::udma::ADC_RX_BUF_SIZE / size_of::()); - scalar.arg1 = adc.read_raw_averaged(channel, averaging) as usize; } } HalOpcode::InvalidCall => { @@ -658,6 +639,9 @@ fn main() { servers::trng::start_trng_service(); servers::rtc::start_rtc_service(); + // start the remaining services + servers::others::start_peri_service(clk_mgr.get_per()); + let tt = ticktimer::Ticktimer::new().unwrap(); // placeholder - we can put an actual service here but for now just sleep the main thread. loop { diff --git a/services/bao1x-hal-service/src/servers.rs b/services/bao1x-hal-service/src/servers.rs index 8f799171f..17e40472e 100644 --- a/services/bao1x-hal-service/src/servers.rs +++ b/services/bao1x-hal-service/src/servers.rs @@ -4,6 +4,7 @@ pub mod keyboard; #[cfg(all(feature = "board-baosec", not(feature = "oem-baosec-lite")))] mod baosec_hw; pub mod bio; +pub mod others; pub mod rtc; pub mod susres; pub mod trng; diff --git a/services/bao1x-hal-service/src/servers/others.rs b/services/bao1x-hal-service/src/servers/others.rs new file mode 100644 index 000000000..6434375ed --- /dev/null +++ b/services/bao1x-hal-service/src/servers/others.rs @@ -0,0 +1,95 @@ +//! Server for all the other hardware pieces that aren't covered by +//! existing well-known/shared service providers, and which also can't +//! be condensed into the main loop due to dependencies on core HAL +//! services (such as IFRAM resolution, I/O setup, etc.) + +use bao1x_api::{IoxDir, IoxEnable, IoxFunction, PeripheralOpcode, SERVER_NAME_BAO1X_OTHERS, iox::IoSetup}; +use bao1x_hal::udma::{Adc, AdcExtChannel, AdcSource}; +use bao1x_hal_service::UdmaGlobal; + +pub fn start_peri_service(clk_freq: u32) { + let _ = std::thread::spawn({ + move || { + peri_service(clk_freq); + } + }); +} + +fn peri_service(clk_freq: u32) -> ! { + let xns = xous_names::XousNames::new().unwrap(); + // claim the server name + let sid = xns.register_name(SERVER_NAME_BAO1X_OTHERS, None).unwrap(); + + let iox = crate::iox::IoxHal::new(); + let udma_global = UdmaGlobal::new(); + udma_global.udma_clock_config(bao1x_api::PeriphId::Adc, true); + // safety: clocks are turned on, and perclk already configured as so + let mut adc = unsafe { Adc::new(clk_freq) }; + + let mut msg_opt = None; + + loop { + xous::reply_and_receive_next(sid, &mut msg_opt).unwrap(); + let opcode = { + let msg = msg_opt.as_mut().unwrap(); + num_traits::FromPrimitive::from_usize(msg.body.id()).unwrap_or(PeripheralOpcode::InvalidCall) + }; + log::debug!("{:?}", opcode); + match opcode { + PeripheralOpcode::ReadAdcChannel => { + if let Some(scalar) = msg_opt.as_mut().unwrap().body.scalar_message_mut() { + let channel = AdcSource::from_usize(scalar.arg1); + // sets to at least 1, even if the arg is 0 + // max averaging is limited by the size of the ADC buffer + let averaging = + scalar.arg2.max(1).min(bao1x_hal::udma::ADC_RX_BUF_SIZE / size_of::()); + scalar.arg1 = adc.read_raw_averaged(channel, averaging) as usize; + } + } + PeripheralOpcode::EnableChannel => { + if let Some(scalar) = msg_opt.as_mut().unwrap().body.scalar_message_mut() { + let channel: AdcExtChannel = scalar.arg1.into(); + let pin = match channel { + AdcExtChannel::Adc0 => 4, + AdcExtChannel::Adc1 => 5, + AdcExtChannel::Adc2 => 6, + AdcExtChannel::Adc3 => 7, + }; + iox.setup_pin( + bao1x_api::IoxPort::PA, + pin, + Some(IoxDir::Input), + Some(IoxFunction::Gpio), + Some(IoxEnable::Disable), + Some(IoxEnable::Disable), + None, + None, + ); + // dabao boards have a dependency to configure this pin as an input as well. + #[cfg(feature = "board-dabao")] + if channel == AdcExtChannel::Adc0 { + iox.setup_pin( + bao1x_api::IoxPort::PC, + 9, + Some(IoxDir::Input), + Some(IoxFunction::Gpio), + Some(IoxEnable::Disable), + Some(IoxEnable::Disable), + None, + None, + ); + } + } + } + PeripheralOpcode::UpdatePerclk => { + if let Some(scalar) = msg_opt.as_mut().unwrap().body.scalar_message_mut() { + let new_perclk = scalar.arg1 as u32; + adc.update_perclk(new_perclk); + } + } + PeripheralOpcode::InvalidCall => { + log::error!("Invalid opcode received: {:?}", msg_opt); + } + } + } +} From e704477f7972847750d3fb3037c8fd43c5480a26 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 24 Feb 2026 01:34:32 +0800 Subject: [PATCH 08/10] api changes for ADC service --- libs/bao1x-api/src/api.rs | 16 ++++++++++++---- libs/bao1x-api/src/lib.rs | 4 ++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/libs/bao1x-api/src/api.rs b/libs/bao1x-api/src/api.rs index d3ea93384..a305c58eb 100644 --- a/libs/bao1x-api/src/api.rs +++ b/libs/bao1x-api/src/api.rs @@ -53,10 +53,18 @@ pub enum HalOpcode { ConfigureIoxIrq = 11, IrqLocalHandler = 12, - /// Adc operations - // blocking scalar - ReadAdcChannel = 32, - /// Manipulate the OS timer SetPreemptionState = 64, } + +#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)] +#[repr(usize)] +pub enum PeripheralOpcode { + InvalidCall = 0, + UpdatePerclk = 1, + + /// Adc operations + // blocking scalar + ReadAdcChannel = 0x100, + EnableChannel = 0x101, +} diff --git a/libs/bao1x-api/src/lib.rs b/libs/bao1x-api/src/lib.rs index 55b1f573b..fd96b4671 100644 --- a/libs/bao1x-api/src/lib.rs +++ b/libs/bao1x-api/src/lib.rs @@ -49,6 +49,10 @@ pub const SERVER_NAME_KBD: &str = "_Matrix keyboard driver_"; /// Do not change this constant, it is hard-coded into libraries in order to break /// circular dependencies on the IFRAM block. pub const SERVER_NAME_BAO1X_HAL: &str = "_bao1x-SoC HAL_"; +/// Server for peripherals that *also* depend on the core Bao1x HAL. These have to +/// be in a separate server to avoid lock-up issues of the server depending on itself +/// for services. +pub const SERVER_NAME_BAO1X_OTHERS: &str = "_HAL-everthing-else_"; /// Number of boots to trigger the 'audit' command. It's set to be bigger than 1, because /// the chip tester may power cycle the chip during the provisioning process before the From 4a542346c82146460a48a617e5d3c0a6c90abcf3 Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 24 Feb 2026 01:34:54 +0800 Subject: [PATCH 09/10] cleanup names and fixup the init delays --- libs/bao1x-hal/src/udma/adc.rs | 41 ++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/libs/bao1x-hal/src/udma/adc.rs b/libs/bao1x-hal/src/udma/adc.rs index 2f79a4f98..e2a3a8661 100644 --- a/libs/bao1x-hal/src/udma/adc.rs +++ b/libs/bao1x-hal/src/udma/adc.rs @@ -80,13 +80,29 @@ pub mod cr_adc { #[repr(usize)] pub enum AdcExtChannel { /// PA04 / ADC0 - Pa04 = 0, + Adc0 = 0, /// PA05 / ADC1 - Pa05 = 1, + Adc1 = 1, /// PA06 / ADC2 - Pa06 = 2, + Adc2 = 2, /// PA07 / ADC3 - Pa07 = 3, + Adc3 = 3, +} + +impl From for usize { + fn from(ch: AdcExtChannel) -> usize { ch as usize } +} + +impl From for AdcExtChannel { + fn from(val: usize) -> AdcExtChannel { + match val { + 0 => AdcExtChannel::Adc0, + 1 => AdcExtChannel::Adc1, + 2 => AdcExtChannel::Adc2, + 3 => AdcExtChannel::Adc3, + _ => unimplemented!("AdcExtChannel value out of range: {}", val), + } + } } /// ADC measurement source. @@ -109,10 +125,10 @@ impl AdcSource { pub fn from_usize(val: usize) -> AdcSource { match val { 0 => AdcSource::Temperature, - 1 => AdcSource::Ext(AdcExtChannel::Pa04), - 2 => AdcSource::Ext(AdcExtChannel::Pa05), - 3 => AdcSource::Ext(AdcExtChannel::Pa06), - 4 => AdcSource::Ext(AdcExtChannel::Pa07), + 1 => AdcSource::Ext(AdcExtChannel::Adc0), + 2 => AdcSource::Ext(AdcExtChannel::Adc1), + 3 => AdcSource::Ext(AdcExtChannel::Adc2), + 4 => AdcSource::Ext(AdcExtChannel::Adc3), _ => unimplemented!("AdcSource::from_usize: invalid value {}", val), } } @@ -262,7 +278,14 @@ impl Adc { // --- Delays ------------------------------------------------------------- #[cfg(feature = "std")] - fn delay_us(us: u64) { std::thread::sleep(std::time::Duration::from_micros(us)); } + fn delay_us(us: u64) { + if us < 1000 { + // less than 1ms is not reliable in std + std::thread::sleep(std::time::Duration::from_millis(1)); + } else { + std::thread::sleep(std::time::Duration::from_micros(us)); + } + } /// Bare-metal delay stub. #[cfg(not(feature = "std"))] From e47e65b70828e42b8a8605c62d27706f47c1ba4d Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 24 Feb 2026 01:35:16 +0800 Subject: [PATCH 10/10] add test routines for ADC --- apps-dabao/dabao-console/src/cmds/test.rs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/apps-dabao/dabao-console/src/cmds/test.rs b/apps-dabao/dabao-console/src/cmds/test.rs index c220b2773..70924b61e 100644 --- a/apps-dabao/dabao-console/src/cmds/test.rs +++ b/apps-dabao/dabao-console/src/cmds/test.rs @@ -89,6 +89,28 @@ impl<'a> ShellCmdApi<'a> for Test { // run forever, code blocks here wheel.run(None); } + "temp" => { + let adc = bao1x_hal_service::Adc::new(); + let raw_temp = adc.read_raw(bao1x_hal::udma::AdcSource::Temperature, Some(8)); + log::info!( + "raw: {}, temp: {}", + raw_temp, + bao1x_hal::udma::Adc::raw_to_temp_celsius(raw_temp) + ); + } + "adc" => { + let adc = bao1x_hal_service::Adc::new(); + // safety - we have manually checked there are no conflicts with this mapping + unsafe { adc.enable_channel(bao1x_hal::udma::AdcExtChannel::Adc0) }; + loop { + let raw = adc.read_raw( + bao1x_hal::udma::AdcSource::Ext(bao1x_hal::udma::AdcExtChannel::Adc0), + Some(8), + ); + log::info!("raw: {} volts: {:.3}V", raw, bao1x_hal::udma::Adc::raw_to_voltage(raw)); + std::thread::sleep(std::time::Duration::from_millis(500)); + } + } "env" => { log::info!("{:?}", std::env::vars()); }