cancel
Showing results for 
Search instead for 
Did you mean: 

STM32 act as SPI Master and slave for Echo of 1byte Data

adityatiwari
Visitor

MASTER SIDE

 

uint8_t txByte_master = 0xA5; // Byte to send

uint8_t rxByte_master = 0x00; // Received byte

volatile uint16_t count = 0;

uint8_t dummyTx = 0x00;

uint8_t dummyRx = 0x00;

volatile uint8_t spi_ready = 0; // Flag to indicate SPI transfer complete

 

void SystemClock_Config(void);

static void MX_GPIO_Init(void);

static void MX_USART2_UART_Init(void);

static void MX_SPI1_Init(void);

 

int main(void)

{

HAL_Init();

 

MX_GPIO_Init();

MX_USART2_UART_Init();

MX_SPI1_Init();

while (1)

{

spi_ready = 0; // Reset flag

 

// Start SPI communication

HAL_SPI_TransmitReceive_IT(&hspi1, &txByte_master, &rxByte_master, 1);

 

// Wait until the transaction completes

while (spi_ready == 0);

 

// Check if received data is correct

if (rxByte_master== 0xA5) {

HAL_SPI_DeInit(&hspi1);// HAL_GPIO_TogglePin(GPIOC, GPIO_PIN_13); // Blink LED if correct

}

 

HAL_Delay(500); // Delay for visibility

 

}

/* USER CODE END 3 */

}

 

SLAVE SIDE

 

 

uint8_t rxByte_slave = 0x00; // Received byte

uint8_t txByte_slave = 0x00; // Byte to send back (Echo)

uint8_t txByte_slave_check = 0xCE; // Byte to send back for check

volatile uint8_t spi_ready = 0; // Flag to indicate SPI transfer complete

 

 

int main(void)

{

HAL_Init();

MX_GPIO_Init();

MX_USART2_UART_Init();

MX_SPI1_Init();

while (1)

{

spi_ready = 0; // Reset flag

HAL_SPI_Receive_IT(&hspi1, &rxByte_slave, 1);

while (spi_ready == 0);

txByte_slave = rxByte_slave;

spi_ready = 0; // Reset flag

HAL_SPI_Transmit_IT(&hspi1, &txByte_slave, 1);

while (spi_ready == 0);

}

}

 

void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi) {

if (hspi->Instance == SPI1) {

spi_ready = 1; // Set flag indicating reception complete

}

}

 

void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) {

if (hspi->Instance == SPI1) {

spi_ready = 1; // Set flag indicating transmission complete

}

}

 

Above written code is for master and slave in which I am trying to echo 1 Byte of Data

through SPI Protocol, here on I am able to capture exact 8 bit of data on slave side but

when slave transmit the same data to master, then master is unable to capture the exact data

and capture some random data .

try to help me in order to solve this problem....

Both side means Master and Slave the board I am using is NUCLEO-F401RE

 

Note :

I have set the slave side on External oscillator.

 

 

 

 

1 REPLY 1
gbm
Lead III

Have a look at this:

https://community.st.com/t5/stm32-mcus-products/regarding-function-calls-when-performing-spi-communication-in/m-p/738412#M265178

My STM32 stuff on github - compact USB device stack and more: https://github.com/gbm-ii/gbmUSBdevice