Problems with SPI communication

20 Feb 2012

Hey people, i'm trying to make communication between two mbeds through SPI, but I'm having problems with the master input slave output, I mean,the slave receives the data from the master, performs a simple addition and should return the value of the addition, but it doesn't return any value to the master. The codes follow:

Master:

  1. include "mbed.h"

SPI spi(p11, p12, p13); mosi, miso, sclk DigitalOut cs(p14);

Serial pc(USBTX, USBRX); tx, rx

int main() { Setup the spi for 8 bit data, high steady state clock, second edge capture, with a 1MHz clock rate spi.format(8,0); spi.frequency(1000000); int teste, result;

teste=0xAA;

cs=0; pc.printf("Answer before = %d\n\r", teste);

wait(5); spi.write(teste); result= spi.write(0x00);

pc.printf("Answer later= 0x%X\n\r", result); cs=1;

}

Slave:

  1. include "mbed.h"

SPISlave slave(p11,p12,p13,p14);

Serial pc(USBTX, USBRX);

int main() {

slave.format(8,0); slave.frequency(1000000); int v, res;

while(1) {

if(slave.receive()) {

v = slave.read(); Read byte from master pc.printf("v=%d\n\r", v); res=(v+5); Add 5 to it slave.reply(res); Make this the next reply pc.printf("v++=%d\n\r", res); } }

}

Please, if anyone could help, I'd very much apprecite it.

20 Feb 2012

First a hint: your code becomes more readable when you use the <<code>> and <</code>> formatting (see editing tips link below).

The problem you see may be caused by the CS from your Master. The CS is the trigger to tell the receiver that the master is done transmitting. You may not see the slave.receive() until CS goes high again. However, you dont send anymore data after CS goes high so the slave never sends anything back.

//send first byte
cs=0;
pc.printf("Answer before = %d\n\r", teste);
spi.write(teste);
cs=1;

//send dummy second byte and receive answer
cs=0;
result= spi.write(0x00);
pc.printf("Answer later= 0x%X\n\r", result); 
cs=1;

You may also want to repeat the transmission on the master side by using an endless while loop similar to the slave.

Note this is just my guess, havent tried the code...

27 Feb 2012

Thnaks a lot, that really actually worked, the only thing is that i needed a delay between cs=0; e cs=1;

27 Feb 2012

Thanks a lot, that really actually worked, the only thing is that i needed a delay between cs=0; e cs=1;