Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
9 years, 3 months ago.
How to enable duplex SPI communication with two F401RE boards?
Hi
Could you please help me to setup a duplex communication i.e. How can I read data sent by slave SPI board? So far, I have been able to send data from master to slave and the code is as follows:
Thanks a lot
//======================== SPI Master==================================== #include "mbed.h" Serial pc(USBTX, USBRX); SPI deviceMaster (PB_5, PB_4, PB_3);// mosi, miso, sclk DigitalOut cs(PA_9); int main() { pc.printf("Communicating with PC...\n"); cs = 1; // Chip must be deselected deviceMaster.format(8,2); deviceMaster.frequency(1000000); int values[5] = {0, 5, -15, 10, 55}; int i = 0; int val = 0; while(1) { if (i < 4){ i++; } else { i = 0; } val = values[i]; cs = 0; // Select the device by seting chip select low deviceMaster.write(val); cs = 1; //int value = deviceMaster.read(); pc.printf("Master Transmission...\n"); pc.printf("%d \r\n", val); wait_us(1000000); } } //======================== SPI Slave ==================================== // Reply to a SPI master as slave #include "mbed.h" #include <SPISlave.h> Serial pc(USBTX, USBRX); SPISlave device(PB_5, PB_4, PB_3, PA_4); // mosi, miso, sclk, ssel int main() { pc.printf("Communicating with PC...\n"); int v = 0; device.format(8,2); device.frequency(1000000); device.reply(0x00); // Prime SPI with first reply while(1) { if(device.receive() == 1) { v = device.read(); // Read byte from master //device.reply(v); // Make this the next reply pc.printf("Slave Transmission...\n"); pc.printf("%d \r\n", v); } } }
1 Answer
8 years, 8 months ago.
The SPI Master is always in control of the communication with the Slave. A Slave can never send data on its own initiative. It will send its data while it receives a byte from the Master. Try this code
//Master .... char slavedata; cs = 0; // Select the device by setting chip select low slavedata = deviceMaster.write(val); // Master is sending and receiving at the same time cs = 1; pc.printf("Master Received..%d\r\n", slavedata); ... // Reply to a SPI master as slave ... device.reply(0x00); // Prime SPI with first reply, this data will be send to the Master if (device.receive() == 1) { // check to see if anything was received from the Master v = device.read(); // Read byte from master //device.reply(v); // Make this the next reply pc.printf("Slave Received..%d\r\n", v); } ...