View previous topic :: View next topic |
Author |
Message |
MeRKeZ
Joined: 04 Sep 2012 Posts: 11
|
Spi communication between two PIC's |
Posted: Tue Dec 16, 2014 5:46 am |
|
|
Hi friends,
I'm developing a project two pic communicates via SPI in, but I have a problem. I send 8 bytes from master to slave and I get eight bytes from slave. I can't get first byte from slave properly. The others are fine. I must get 0 as a first byte but I get 49 which is the ascii value of '1'. How can I solve this problem?
Thanks in advance
Master
Code: |
output_low(Slave1);
spi_write('1');
output_high(Slave1);
for(i=0;i<8;i++)
{
if(control==1)
{
control = 0;
receivedData = 0;
output_low(Slave1);
spi_write(data[i]);
while(!spi_data_is_in());
receivedData = spi_read();
output_high(Slave1);
control= 1;
printf(lcd_putc,"\fdata: %d",receivedData);
delay_ms(500);
}
}
|
Slave
Code: |
if(spi_data_is_in())
{
data = spi_read();
delay_ms(5);
if(data == '1')
{
for(i=0;i<8;i++)
{
while(!spi_data_is_in());
data = spi_read();
delay_ms(5);
spi_write(i);
}
}
}
|
|
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19539
|
|
Posted: Tue Dec 16, 2014 9:37 am |
|
|
Key problem is understanding how SPI works.
With SPI, the master clocks a byte out, and receives back, what was _already loaded_ in the slave register.
In your case, you send '1', so this is in the slave's register. You need to load the slave's register with the first byte, as soon as the '1' is received, not _after_ the next transaction. So:
Code: |
if(spi_data_is_in())
{
data = spi_read();
//Don't delay. The slave is synchronised by the master
if(data == '1')
{
for(i=0;i<8;i++)
{
spi_write(i); //Write the byte _ahead_ of the transaction
while(!spi_data_is_in());
data = spi_read();
//again don't delay
}
}
}
|
You have to 'think ahead' each time, loading the next byte _before_ the master clocks a transaction. |
|
|
MeRKeZ
Joined: 04 Sep 2012 Posts: 11
|
|
Posted: Tue Dec 16, 2014 11:50 am |
|
|
@Ttelmah
Thank you so much for helping. I both solved the problem and understand how it works clearly thanks to you. Thank you |
|
|
|