Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ESP32(SPI): Disable the write side when reading is being done in DMA … #1894

Merged
merged 3 commits into from
Aug 7, 2024

Conversation

JurajSadel
Copy link
Contributor

…mode

Thank you for your contribution!

We appreciate the time and effort you've put into this pull request.
To help us review it efficiently, please ensure you've gone through the following checklist:

Submission Checklist 📝

  • I have updated existing examples or added new ones (if applicable).
  • I have used cargo xtask fmt-packages command to ensure that all changed code is formatted correctly.
  • My changes were added to the CHANGELOG.md in the proper section.
  • My changes are in accordance to the esp-rs API guidelines

Extra:

Pull Request Details 📖

Description

This PR is based on @Dominaezzz's suggestion from #1860 (comment).

Testing

//! Connect MISO and MOSI pins
//!
//! The following wiring is assumed:
//! SCLK => GPIO0
//! MISO => GPIO2
//! MOSI => GPIO4

//% CHIPS: esp32 esp32c2 esp32c3 esp32c6 esp32h2 esp32s2 esp32s3
//% FEATURES: async embassy embassy-generic-timers embedded-hal embedded-hal-bus/async

#![no_std]
#![no_main]

use embassy_executor::Spawner;
use embassy_time::{Duration, Timer};
use embedded_hal::spi::Operation;
use embedded_hal_async::spi::SpiDevice;
use embedded_hal_bus::spi::ExclusiveDevice;
use esp_backtrace as _;
use esp_hal::{
    clock::ClockControl,
    dma::*,
    dma_descriptors,
    gpio::{Io, Level, Output},
    peripherals::Peripherals,
    prelude::*,
    spi::{
        master::{dma::SpiDma, prelude::*, Spi},
        FullDuplexMode,
        SpiMode,
    },
    system::SystemControl,
    timer::{timg::TimerGroup, ErasedTimer, OneShotTimer},
    Async,
    FlashSafeDma,
};
use esp_println::println;

// When you are okay with using a nightly compiler it's better to use https://docs.rs/static_cell/2.1.0/static_cell/macro.make_static.html
macro_rules! mk_static {
    ($t:ty,$val:expr) => {{
        static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
        #[deny(unused_attributes)]
        let x = STATIC_CELL.uninit().write(($val));
        x
    }};
}

const DMA_BUF: usize = 256;

#[cfg(not(any(feature = "esp32", feature = "esp32s2")))]
type SafeSpiDma = FlashSafeDma<
    SpiDma<'static, esp_hal::peripherals::SPI2, DmaChannel0, FullDuplexMode, Async>,
    DMA_BUF,
>;

#[cfg(any(feature = "esp32", feature = "esp32s2"))]
type SafeSpiDma = FlashSafeDma<
    SpiDma<'static, esp_hal::peripherals::SPI2, Spi2DmaChannel, FullDuplexMode, Async>,
    DMA_BUF,
>;

#[esp_hal_embassy::main]
async fn main(_spawner: Spawner) {
    esp_println::println!("Init!");
    let peripherals = Peripherals::take();
    let system = SystemControl::new(peripherals.SYSTEM);
    let clocks = ClockControl::boot_defaults(system.clock_control).freeze();

    let timg0 = TimerGroup::new(peripherals.TIMG0, &clocks);
    let timer0: ErasedTimer = timg0.timer0.into();
    let timers = [OneShotTimer::new(timer0)];
    let timers = mk_static!([OneShotTimer<ErasedTimer>; 1], timers);
    esp_hal_embassy::init(&clocks, timers);

    let io = Io::new(peripherals.GPIO, peripherals.IO_MUX);
    let sclk = io.pins.gpio0;
    let miso = io.pins.gpio2;
    let mosi = io.pins.gpio4;
    let cs = io.pins.gpio5;

    let dma = Dma::new(peripherals.DMA);

    #[cfg(any(feature = "esp32", feature = "esp32s2"))]
    let dma_channel = dma.spi2channel;
    #[cfg(not(any(feature = "esp32", feature = "esp32s2")))]
    let dma_channel = dma.channel0;

    let (descriptors, rx_descriptors) = dma_descriptors!(32000);

    let mut spi = Spi::new(peripherals.SPI2, 100.kHz(), SpiMode::Mode0, &clocks)
        .with_pins(Some(sclk), Some(mosi), Some(miso), Some(cs))
        .with_dma(
            dma_channel.configure_for_async(false, DmaPriority::Priority0),
            descriptors,
            rx_descriptors,
        );

    let cs = Output::new(io.pins.gpio18, Level::Low);

    let spi: SafeSpiDma = FlashSafeDma::new(spi);
    let mut spi_dev = ExclusiveDevice::new(spi, cs, embassy_time::Delay).unwrap();

    loop {
        let write_buf = &[1];
        let payload = &[5, 4, 3, 2, 1];

        println!("SPI 2 (write buffer)... ");
        let mut ops = [Operation::Write(write_buf), Operation::Write(payload)];
        let _ = spi_dev.transaction(&mut ops).await;

        println!("SPI 3 (read previous buffer)...");
        let mut read: [u8; 6] = [0x00u8; 6];
        let mut ops = [Operation::Read(&mut read)];
        let _ = spi_dev.transaction(&mut ops).await;
        println!("... result: {:?}", read);

        Timer::after(Duration::from_millis(1_000)).await;
    }
}

now prints

Init!
SPI 2 (write buffer)... 
SPI 3 (read previous buffer)...
... result: [0, 0, 0, 0, 0, 0]
SPI 2 (write buffer)... 
SPI 3 (read previous buffer)...
... result: [0, 0, 0, 0, 0, 0]
SPI 2 (write buffer)... 
SPI 3 (read previous buffer)...
... result: [0, 0, 0, 0, 0, 0]

closes #1860

@JurajSadel JurajSadel added the skip-changelog No changelog modification needed label Aug 1, 2024
@JurajSadel JurajSadel removed the skip-changelog No changelog modification needed label Aug 2, 2024
@JurajSadel
Copy link
Contributor Author

I will add a HIL test for this as well.

Copy link
Collaborator

@Dominaezzz Dominaezzz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM FWIW

@ProfFan
Copy link
Contributor

ProfFan commented Aug 6, 2024

Gently ping

Copy link
Member

@MabezDev MabezDev left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks!

@jessebraham jessebraham added this pull request to the merge queue Aug 7, 2024
Merged via the queue into esp-rs:main with commit 54ee364 Aug 7, 2024
19 checks passed
AnthonyGrondin pushed a commit to AnthonyGrondin/esp-hal that referenced this pull request Aug 8, 2024
esp-rs#1894)

* ESP32(SPI): Disable the write side when reading is being done in DMA mode

* disable and re-enable MISO and MOSI in write and transfer methods

* changelog
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Async-SPI on ESP32: Unexpected behavior
6 participants