imxrt-rs / imxrt-hal

Rust for NXP i.MX RT
Apache License 2.0
133 stars 33 forks source link

Spurious CS high when using SPI enable_chip_select_0 #111

Closed algesten closed 1 year ago

algesten commented 3 years ago

I've been debugging an SPI problem for the last week, and in the end I ended up buying a logic analyzer to hunt the problem down.

The problem seems to stem from using enable_chip_select_0 instead of taking control over the CS myself.

I apologize in advance if the problem isn't in imxrt-hal, I've tried to follow the code, but I don't quite get how this specific feature works.

The code in question is this:

    let (_, _, _, spi4_builder) = p.spi.clock(
        &mut p.ccm.handle,
        ccm::spi::ClockSelect::Pll2,
        ccm::spi::PrescalarSelect::LPSPI_PODF_5,
    );

    let mut spi = spi4_builder.build(pins.p11, pins.p12, pins.p13);

    spi.set_clock_speed(bsp::hal::spi::ClockSpeed(1_000_000))
        .unwrap();

    spi.enable_chip_select_0(pins.p10);

    spi.set_mode(spi::MODE_0).unwrap();
    spi.clear_fifo();

// and later (using u16, since my chip uses that by default)

        let mut buf2 = [0x4100, 0];
        spi.transfer(&mut buf2)?;

Recording this with the logic analyzer I get this:

Screen Shot 2021-07-05 at 18 37 11 2

Notice how the white CS goes to high in between word 1 and word 2. I believe this not correct and the chip I'm working with (an IO-expander MCP23S17), does not like it at all.

The workaround is to take control over the CS myself, so quite easily solved once I saw the problem, but I wonder whether the behavior of method.enable_chip_select_0 can be fixed?

mciantyre commented 3 years ago

Thanks for the detailed report! These observations are consistent with how I've seen this SPI peripheral manage the chip select pin. Since the CS pin is fully managed by the hardware, changing the behavior requires us to study the reference manual, and understand what settings are available. It's definitely an imxrt-hal issue, so you're in the right place.

Besides driving CS manually, there might be two other options:

mciantyre commented 1 year ago

This should be resolved in imxrt-hal v0.5. The LPSPI driver now uses continuous transfers for blocking u8/u16/u32 exchanges and writes. Chip select remains asserted throughout the entire transfer.

The images below (click to expand) show logic analyzer recordings of the hal_spi example that exchanges this buffer

https://github.com/imxrt-rs/imxrt-hal/blob/4bee9504c533bec3c2e065a152973cef7f7df39c/examples/hal_spi.rs#L65

where Elem is one of

u8 hal_spi_u8
u16 hal_spi_u16
u32 hal_spi_u32
algesten commented 1 year ago

Excellent! Thanks!