Not getting correct values from SPI_ReadData()

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Not getting correct values from SPI_ReadData()

730 Views
gavinsmith
Contributor II

Hi, trying to use the SPI for single byte read / write operations using Kinetis MKL16Z128VFM4 and sdk2.0

When using SPI_ReadData, the values seem to be one byte behind what I expect.

 

Here is my config, send and receive functions.

 

//Setup SPI for radio
spi_master_config_t config;
SPI_MasterGetDefaultConfig(&config);
config.pinMode = kSPI_SlaveSelectAsGpio;
config.baudRate_Bps = 50000;
SPI_MasterInit(SPI0, &config, CLOCK_GetFreq(kCLOCK_PllFllSelClk));
SPI_Enable (SPI0, true);

 

void SPIPut(unsigned char v)
{
volatile DWORD StatusFlags;
DWORD ulDummy;
DWORD Byte;
//ulDummy = SPI_ReadData(SPI0);
Delay10us(1);
SPI_WriteData(SPI0,v);
while (0 == (SPI_GetStatusFlags (SPI0) & kSPI_TxBufferEmptyFlag)); // wait for data to be sent.
Delay10us(1000);
ulDummy = SPI_ReadData(SPI0);
}


BYTE SPIGet(void)
{
WORD RxData;
Delay10us(100);
SPI_WriteData(SPI0,SPI_DUMMYDATA);
while (0 == (SPI_GetStatusFlags (SPI0) & kSPI_TxBufferEmptyFlag)); // wait for data to be sent.
while (0 == (SPI_GetStatusFlags (SPI0) & kSPI_RxBufferFullFlag)); // wait for data to be received.
Delay10us(1000);
RxData = SPI_ReadData(SPI0);
Delay10us(1000);
return (BYTE)(RxData);
}

 

To read a register from my slave device, i send it the register address using SPIPut, then do an SPIGet to read the register value.

when reading the registers say 0 - 5, I expect to get

0x28

0x88

0x03

0x07

0x0C

and my scope confirms that this is what is being sent.

 

but what I actually get from the SPI_ReadData function is

0x28

0x28

0x88

0x03

0x07

0x0C

So the 1st byte reads correctly, then all subsequent bytes are out by one. Its almost like there is a buffer somewhere. Any ideas what I am doing wrong?

Labels (1)
Tags (1)
0 Kudos
Reply
1 Reply

490 Views
kerryzhou
NXP TechSupport
NXP TechSupport

Hi Gavin Smith,

  Please modify your code:

BYTE SPIGet(void)
{
WORD RxData;
Delay10us(100);

while (0 == (SPI_GetStatusFlags (SPI0) & kSPI_TxBufferEmptyFlag)); // wait for data to be sent.

SPI_WriteData(SPI0,SPI_DUMMYDATA);
while (0 == (SPI_GetStatusFlags (SPI0) & kSPI_RxBufferFullFlag)); // wait for data to be received.
RxData = SPI_ReadData(SPI0);
Delay10us(1000);
return (BYTE)(RxData);
}

Then test it again.

If you still have problem.

    Please also give us the main code you write in the master and the SPI wave in the SPI bus.


Have a great day,
Kerry

-----------------------------------------------------------------------------------------------------------------------
Note: If this post answers your question, please click the Correct Answer button. Thank you!
-----------------------------------------------------------------------------------------------------------------------

0 Kudos
Reply