Question about communication between two mcu via spi[Solved]

For general Flowcode discussion that does not belong in the other sections.
mnfisher
Valued Contributor
Posts: 1626
http://meble-kuchenne.info.pl
Joined: Wed Dec 09, 2020 9:37 pm
Has thanked: 142 times
Been thanked: 757 times

Re: Question about communication between two mcu via spi

Post by mnfisher »

This is caused by the synchronous transfer of data (as mentioned above)

So while the slave is receiving the first byte of data (10) the value set in the last transmission is being sent. So this will be the last byte from the the previous data block (here 128).

So the received data is always 'off by one'.

The simplest solution is to ignore the first byte of the reply and send an extra 'dummy' byte at the end of transmission.

For example

Data to send by slave = {1,2,3,4,5} (5 bytes expected)

Master sends {1,2,3,4,5,6} (6 bytes including an extra 'final' value)

Slave replies with {x,1,2,3,4,5} and the master 'ignores' x. (5 bytes received + 'x' on first byte received)

The alternative is to 'preload' the SPI send buffer with the first byte of the reply - though this might be unknown (whether a sensor reading or based on the data received from the master) - but you could possibly use the CS going low to 'wake' the slave and do the preload. Depending on application - the slave may sleep the MCU to save power until data is requested by master (CS - goes low - data send in response to master - master pulls CS high - slave sleeps)

Also in the slave interrupt:

Try:

SPI_SendChar(); (or SPI_Slave_Calc())
SPI_Slave::GetChar() // This receives AND sends a data byte (which is set by SendChar())

Martin

seokgi
Posts: 217
Joined: Thu Dec 03, 2020 1:43 pm
Has thanked: 6 times
Been thanked: 7 times

Re: Question about communication between two mcu via spi

Post by seokgi »

Thanks to your help, I've solved the problem.

I'm posting my project for your reference.
Attachments
250811-Main-PIC24FJ512GA606_SPI_Master_Forum.fcfx
(63.73 KiB) Downloaded 79 times
250811-18F45K40-SPI_Slave_Forum.fcfx
(39.28 KiB) Downloaded 42 times

seokgi
Posts: 217
Joined: Thu Dec 03, 2020 1:43 pm
Has thanked: 6 times
Been thanked: 7 times

Re: Question about communication between two mcu via spi[Solved]

Post by seokgi »

I would like to know the exact usage of TransactionArray.

mnfisher
Valued Contributor
Posts: 1626
Joined: Wed Dec 09, 2020 9:37 pm
Has thanked: 142 times
Been thanked: 757 times

Re: Question about communication between two mcu via spi[Solved]

Post by mnfisher »

Glad you have it working .

TransactionArray allows you to send and receive an array of data without using a loop.

Code: Select all

byte array data_out[10]  Can set intial value {1,2,3,..10} or assign in code (data_out[0] = 1
data_out[1] = 2 etc)
byte array data_in[10]
Then TransactionArray(data_out, data_in, 10) will send data_out (10 bytes) and receive data_in.
Martin

Post Reply