Trying to move the ADC reader code to a separate function

This commit is contained in:
Thomas Kolb 2023-01-04 13:30:30 +01:00
parent 1a6e442815
commit 8790a7ce04

View file

@ -54,6 +54,27 @@ const HIGH: u16 = 25000;
/// if your board has a different frequency /// if your board has a different frequency
const XTAL_FREQ_HZ: u32 = 12_000_000u32; const XTAL_FREQ_HZ: u32 = 12_000_000u32;
fn get_adc_channel_blocking<S, D, const DS: u8, E>(dma: &hal::dma::Channels, spi: &mut rp2040_hal::Spi<S, D, DS>, cs_pin: &dyn embedded_hal::digital::v2::OutputPin<Error = E>) -> 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. /// Entry point to our bare-metal application.
/// ///
/// The `#[rp2040_hal::entry]` macro ensures the Cortex-M start-up code calls this function /// 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); let dma = pac.DMA.split(&mut pac.RESETS);
// Use DMA to read ADC (0xC0 in byte 1 is the channel mask) // Use DMA to read ADC (0xC0 in byte 1 is the channel mask)
let tx_buf = singleton!(: [u8; 3] = [0x06, 0x40, 0x00]).unwrap(); //let tx_buf = singleton!(: [u8; 3] = [0x06, 0x40, 0x00]).unwrap();
let rx_buf = singleton!(: [u8; 3] = [0; 3]).unwrap(); //let rx_buf = singleton!(: [u8; 3] = [0; 3]).unwrap();
// clear chip select let adc_value = get_adc_channel_blocking(&dma, &mut spi, &spi_cs);
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 data: String<16> = String::from(adc_value); let data: String<16> = String::from(adc_value);