2021-01-29 03:14 AM
I need to send data one byte at a time via SPI. After transferring the byte, I set "Chip Select" from the program to state 1. I track the end of the transfer by the BSY bit in the SPI_SR register. But the microcontroller transmits two bytes, the first byte is the value from the DR register and the second byte 0. The transmission length is set to 8 bits. I tried to set a different transmission length, but the microcontroller always sends two transmissions of the length I set. Below is the initialization code.
RCC-> APB2ENR | = RCC_APB2ENR_SPI4EN;
// CPHA = 1 // CPOL = 1
SPI4-> CR1 =
SPI_CR1_BR_1 | SPI_CR1_BR_2 | SPI_CR1_BR_0 | // Baud rate = Fpclk / 256
SPI_CR1_MSTR |
SPI_CR1_CPOL |
SPI_CR1_CPHA |
SPI_CR1_SSM |
SPI_CR1_SSI;
SPI4-> CR2 = SPI_CR2_DS_0 | SPI_CR2_DS_1 | SPI_CR2_DS_2;
SPI4-> CR1 | = SPI_CR1_SPE;
Send data
LCD_CS_Clr();
_delay_us(2);
SPI4->DR = data;
while((SPI4->SR & SPI_SR_BSY) != 0);
_delay_us(2);
LCD_CS_Set();
_delay_us(2);
Solved! Go to Solution.
2021-01-29 03:18 AM
The assignment SPI4->DR = data; is wider than 8-Bits so 2 bytes are sent.
Try
*(__IO uint8_t*)(&SPI4->DR) = data;
hth
KnarfB
2021-01-29 03:18 AM
The assignment SPI4->DR = data; is wider than 8-Bits so 2 bytes are sent.
Try
*(__IO uint8_t*)(&SPI4->DR) = data;
hth
KnarfB
2021-01-29 03:27 AM
Thanks KnarfB, it really works.
I am using data of type uint8_t. How does DR register type conversion affect transfer?
2021-01-29 03:51 AM
Probably the SPI IP evaluates the byte lanes from the access protocoll..
2021-01-29 04:02 AM
The definition of SPI DR in CMSIS is
__IO uint32_t DR;
which makes it a 32-bit type variable (8 bit would not be enough for all possible SPI data sizes, up to 16 bit are possible).
Therefore, data is promoted to an unsigned int in the assignment and data is stored using a 32-bit STR instruction.
But, the SPI DR register HW is implemented that it switches to 8-bit only if 8-bit are written (STRB instruction).
hth
KnarfB
2021-01-29 04:57 AM
Thanks, it helped me a lot.
2021-01-29 04:59 AM
I solved the problem. KnarfB's suggestion helped.