add draft ADC support to hal service

This commit is contained in:
bunnie 2026-02-23 18:53:37 +08:00
parent 302b7b65bf
commit 18e72a970c
2 changed files with 59 additions and 1 deletions

View file

@ -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>) -> u16 {
let averaging =
averaging.unwrap_or(1).min(1).max((bao1x_hal::udma::ADC_RX_BUF_SIZE / size_of::<u32>()) 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,
}

View file

@ -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<IrqLocalRegistration>; 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::<u32>());
scalar.arg1 = adc.read_raw_averaged(channel, averaging) as usize;
}
}
HalOpcode::InvalidCall => {
log::error!("Invalid opcode received: {:?}", msg_opt);
}