Slower SPI Slave Read

I am new to mbed so this question may seem very basic. I have SPI master-slave setup with FRDM-K64F board and FPGA board. In my setup FRDM-K64F is SPI slave and FPGA is spi master. I want to read data coming from master to slave. This is a simple code running on FRDM-K64F board which is slave in my setup.

#include "mbed.h" #define DATA_BUFFER_SIZE 10000

int main()
{
int bytes_count = 0;
SPISlave spi_slave_device(PTD2, PTD3, PTD1, PTD0);
spi_slave_device.format(8, 0);
spi_slave_device.frequency(2000000);
int reply = 0x00;
spi_slave_device.reply(reply);
char* inputBuffer = new char[DATA_BUFFER_SIZE];
printf(“Reading data from master\r\n”);

while (1)
{
    if (spi_slave_device.receive())
    {
        if (bytes_count < DATA_BUFFER_SIZE)
        {
            inputBuffer[bytes_count++] = spi_slave_device.read();
        }
        else
        {
            break;
        }
    }
}

printf("Data received\r\n");

for (int i = 0; i < DATA_BUFFER_SIZE; i++)
{
    printf("%02X ", inputBuffer[i]);
    if (i % 50 == 0)
    {
        printf("\r\n");
    }
}

if (inputBuffer != NULL)
{
    delete [] inputBuffer;
}

return 0;

}

On FPGA there is SPI master application which is sending data to slave. This master is running at 2MHz frequence with SPI mode 0. I am able to receive bytes on SPI Slave but the problem is i see some bytes are missing on the slave side.

To verify this i used a logic analyzer instead of SPI slave program and i can see all the data from master is being received on SPI slave pins. I am using online mbed compiler to build my program. It seems like “read” operation in SPISlave is not fast enough to receive all the bytes from master. Has anyone seen this issue? Is there a way to increase read operation from spi slave side?

You need to use an interrupt function to get the data particularly at 2Mhz.

I haven’t tried SPI slave but must be similar to Serial.
I use something like this maybe.

void data_callback() {   
    while (connected_device.readable()){data_buff[bufferIndex] = connected_device.getc();bufferIndex++;}
    connected_device_has_data=1;
}

connected_device.attach(data_callback);

Thanks for the reply @star297. For serial interface there is an interrupt function but for SPI slave i don’t see any interrupt function as such. I referred SPISlave - APIs | Mbed OS 5 Documentation and i can see “read” is the only API to get data from SPI master. Please correct me if i am wrong here.

Yes, it looks like SPI is different, I think you need to use the CS (chip select) line as a hardware trigger for the read function. Probably because of the higher SPI speeds, hardware interrupt would be faster.
We do have similar for the Serial, RTS and CTS but tend not to use these.

Have a look here, similar questions and there’s some example code.

https://os.mbed.com/forum/mbed/topic/2718/?page=1

https://os.mbed.com/questions/61096/Attach-interrupt-to-SPI-Slave/