From 8790a7ce049f06d2bb356cb649714c29624c20f1 Mon Sep 17 00:00:00 2001 From: Thomas Kolb Date: Wed, 4 Jan 2023 13:30:30 +0100 Subject: [PATCH] Trying to move the ADC reader code to a separate function --- src/main.rs | 36 ++++++++++++++++++++++++------------ 1 file changed, 24 insertions(+), 12 deletions(-) diff --git a/src/main.rs b/src/main.rs index 2c88e6d..6c45033 100644 --- a/src/main.rs +++ b/src/main.rs @@ -54,6 +54,27 @@ const HIGH: u16 = 25000; /// if your board has a different frequency const XTAL_FREQ_HZ: u32 = 12_000_000u32; +fn get_adc_channel_blocking(dma: &hal::dma::Channels, spi: &mut rp2040_hal::Spi, cs_pin: &dyn embedded_hal::digital::v2::OutputPin) -> u16 +where + S: hal::spi::State, + D: hal::spi::SpiDevice, + E: core::fmt::Debug +{ + let mut tx_buf: [u8; 3] = [0x06, 0x40, 0x00]; + let mut rx_buf: [u8; 3] = [0; 3]; + + // clear chip select + cs_pin.set_low().unwrap(); + + // Use BidirectionalConfig to simultaneously write to spi from tx_buf and read into rx_buf + let transfer = bidirectional::Config::new((dma.ch0, dma.ch1), &tx_buf, spi, &rx_buf).start(); + // Wait for both DMA channels to finish + let ((_ch0, _ch1), tx_buf, _spi, rx_buf) = transfer.wait(); + cs_pin.set_high().unwrap(); + + (((rx_buf[1] & 0x0F) as u16) << 8) | rx_buf[2] as u16 +} + /// Entry point to our bare-metal application. /// /// The `#[rp2040_hal::entry]` macro ensures the Cortex-M start-up code calls this function @@ -170,19 +191,10 @@ fn main() -> ! { let dma = pac.DMA.split(&mut pac.RESETS); // Use DMA to read ADC (0xC0 in byte 1 is the channel mask) - let tx_buf = singleton!(: [u8; 3] = [0x06, 0x40, 0x00]).unwrap(); - let rx_buf = singleton!(: [u8; 3] = [0; 3]).unwrap(); + //let tx_buf = singleton!(: [u8; 3] = [0x06, 0x40, 0x00]).unwrap(); + //let rx_buf = singleton!(: [u8; 3] = [0; 3]).unwrap(); - // clear chip select - spi_cs.set_low().unwrap(); - - // Use BidirectionalConfig to simultaneously write to spi from tx_buf and read into rx_buf - let transfer = bidirectional::Config::new((dma.ch0, dma.ch1), tx_buf, spi, rx_buf).start(); - // Wait for both DMA channels to finish - let ((_ch0, _ch1), tx_buf, _spi, rx_buf) = transfer.wait(); - spi_cs.set_high().unwrap(); - - let adc_value = (((rx_buf[1] & 0x0F) as u16) << 8) | rx_buf[2] as u16; + let adc_value = get_adc_channel_blocking(&dma, &mut spi, &spi_cs); { let data: String<16> = String::from(adc_value);