Reputation: 1
I am currently working on a project that uses an ESP32 as an SPI slave with an Arduino Uno as an SPI master. I'm developing this on platformio
, and using Arduino framework for the ESP32. I came across this library by hideakitai ESP32DMASPI. I am successful in transmitting data from the Uno to the ESP32 (inspired from an example):
while(spi.available())
{
uint8_t data[BUFFER_SIZE] = {0};
for (size_t i = 0; i < BUFFER_SIZE; ++i)
{
data[i] = spi_slave_rx_buf[i];
spi_slave_rx_buf[i] = 0;
}
user_onReceive(data);
spi.pop();
}
I am struggling to implement an "on_request
" function to send (transfer) a byte back to master. How do I go about doing this?
Looking at how SPI works, the MISO line transmits the same data as the MOSI + the extra data added by the slave, is this how this works? Can I implement something like this using ESP32DMASPI?
Any help is greatly appreciated! TIA
Upvotes: 0
Views: 3745
Reputation: 4772
The SPI bus has two peculiar properties.
Firstly, it's full duplex - meaning data flows in both directions (master to slave, slave to master) at the same time. Every time the SCLK line completes a cycle, 1 bit of data is transferred on MISO and the same on MOSI. There are no cases where data flows in only one direction, always in both (obviously the data can be meaningless, or dummy, if there's nothing relevant to send).
Secondly, only the master can trigger data transfers on the SPI bus. This is the tricky part. If the slave has any data to send to the master, it must have this data ready in its transmission queue/buffer. The next time master triggers a data transfer (i.e. clocks the bus), this data gets sent from slave the master (and the same amount of data is transferred in opposite direction, but this can be dummy). The master must take care to clock the bus enough times to read all the data out of the slave.
You have the honor of building a (framing) protocol on top of SPI which takes these properties into account and gets the job done. E.g. perhaps you might want to start each bus transfer with the slave sending the number of bytes of data it's got queued for transmission, so the master knows how much data it needs to clock out of the slave. Or, as a simpler solution, always transfer the minimum amount of bytes to get a message of any size across, then sort out later if there was a message sent or not.
Upvotes: 0