Hardware SPI: Write then read not working



  • I need to write one byte to my SPI peripheral and then read 3 bytes back while keeping CS asserted. My code is given below. Though my peripheral is responding, i'm reading zeroes in my code.

    
            unsigned char writeBuff[1] = { 0x1F };
            unsigned char readBuff[3]{ 42, 42, 42 };
    
            spi_ioc_transfer xfer[2]{};
    
            xfer[0].len = sizeof(writeBuff);
            xfer[0].tx_buf = (unsigned long)(writeBuff);
    
            xfer[1].len = sizeof(readBuff);
            xfer[1].rx_buf = (unsigned long)(readBuff);
    
            int status = ioctl(spiFd, SPI_IOC_MESSAGE(2), &xfer);
            if (status < 0) {
                    printf("ERR: Failed to read %d\n", errno);
                    exit(1);
            }
    
            for (auto i : readBuff) {
                    std::cout << +i << " ";
            }
            std::cout << "\n";
            return 0;
    


  • logic_analyzer.png



  • I'm successfully using an SPI wrapper I wrote several years ago for exactly the same kind of accesses (e.g. for MCP23S17). The routine to perform a read-then-write (or optionally, write-and-write-again) does quite the same as your sample code (see SPIBus::spidev_write_read() at lines 205ff in p44utils/spi.cpp.

    I didn't spot a functional difference to your code, so I'd assume your code should work (I know mine does, its in active use in many projects)

    Maybe there's a difference in how you open the spiFd? You can see that part in SPIBus::accessBus() at line 384ff.

    I'm using this code with both the MT7688 hardware SPI (which has a known hardware bug for full duplex, but that should not apply here, your read data starts after the write is over), and also with spi-gpio-custom software SPI.

    Hope this helps!


Log in to reply
 

Looks like your connection to Community was lost, please wait while we try to reconnect.