SPI Slave randomly ignores bytes from SPI master with interrupt mode
Hello everyone, nice to meet you all. This is my very first post in this community though I 've been programming on stm32 boards for more than a year, so if I make any mistakes, please let me know so that I can improve later. Thanks very much and hope you all have a nice day!!!
My problem is the SPI communication between the blue pill board STM32F103C8T6 (slave) and the Arduino Uno R3 board (master). Here is my setup:
1. For arduino:
The code:
#include <SPI.h>
#define SS 10
void setup() {
Serial.begin(9600);
pinMode(SS, OUTPUT);
SPI.begin();
}
void dataTransfer(uint8_t data) {
digitalWrite(SS, LOW);
SPI.transfer(data);
digitalWrite(SS, HIGH);
}
void loop() {
for(int i = 0; i < 10; i++) {
dataTransfer(i+1);
Serial.print(i+1);
Serial.print("\t");
delay(1000);
}
Serial.print("\n");
}
2. For STM32:
Here is my SPI2 configuration:
static void MX_SPI2_Init(void)
{
hspi2.Instance = SPI2;
hspi2.Init.Mode = SPI_MODE_SLAVE;
hspi2.Init.Direction = SPI_DIRECTION_2LINES;
hspi2.Init.DataSize = SPI_DATASIZE_8BIT;
hspi2.Init.CLKPolarity = SPI_POLARITY_HIGH;
hspi2.Init.CLKPhase = SPI_PHASE_2EDGE;
hspi2.Init.NSS = SPI_NSS_HARD_INPUT;
hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi2.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN SPI2_Init 2 */
/* USER CODE END SPI2_Init 2 */
}

my main.c of stm32:
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_I2C1_Init();
MX_SPI1_Init();
MX_SPI2_Init();
HAL_SPI_Receive_IT(&hspi2, (uint8_t*)spi_data_rx,10);
while (1)
{
while(HAL_SPI_GetState(&hspi1)!=HAL_SPI_STATE_READY);
}
}
I write a file naming spi_slave.c and spi_slave.h to handle incoming data using interrupt, this is the .c one and the .h is empty:
#include "main.h"
#include "spi_slave.h"
extern SPI_HandleTypeDef hspi2;
#define spi_rxsize 10
char spi_data_rx[spi_rxsize];
uint8_t spi_rxcount = 0;
int spi_countAddr = 0;
int spi_countrxcplt = 0;
int spi_counterror = 0;
void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi)
{
if(hspi->Instance == SPI2)
{
HAL_SPI_Receive_IT(&hspi2, (uint8_t*)spi_data_rx, 10);
}
}
void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi) {
spi_counterror++;
}
Though I send 10 numbers from Arduino, I still miss some numbers when my stm32 reads them
3. Some useful images:

STM32 clock configuration:

