2020-06-16 08:15 AM
i'm trying to send data using SPI. i'm getting started with a simple example with is a loopback test. so when i used the HAL_transmitReceive(..) it worked pretty well but when i tried to use it in interrupt mode the last byte of the array that i'm sending is forced to zero only if the number of data of the array is impair other wise it shows correctly the last value.( for example if i send {1,2,3} i recieve {1,2,0} and if i send {1,2,3,4} i receive {1,2,3,4}). I placed two counters in the SPI_IRQ Handler to see how many times the interrupt is executed but it shows some weird values. here's my code.
Main
int main(void)
{
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration----------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_SPI1_Init();
/* USER CODE BEGIN 2 */
HAL_SPI_TransmitReceive_IT(&hspi1,(uint8_t*)&buffer_Tx,(uint8_t*)&buffer_Rx,(sizeof(buffer_Rx)/sizeof(uint8_t)));
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
}
/* USER CODE END 3 */
}
Interrupt
int Tx=0;
int Rx=0;
void SPI1_IRQHandler(void)
{
/* USER CODE BEGIN SPI1_IRQn 0 */
if(__HAL_SPI_GET_FLAG(&hspi1,SPI_FLAG_RXNE))
{
Rx+=1;
} else
if(__HAL_SPI_GET_FLAG(&hspi1,SPI_FLAG_TXE))
{
Tx+=1;
}
/* USER CODE END SPI1_IRQn 0 */
HAL_SPI_IRQHandler(&hspi1);
/* USER CODE BEGIN SPI1_IRQn 1 */
/* USER CODE END SPI1_IRQn 1 */
}
2020-06-16 09:28 AM
Which STM32?
Sounds like you use some of the newer STM32 which has "data packing" or FIFO on the SPI. Read carefully the SPI chapter in RM.
JW
2020-06-16 09:35 AM
First of all, all variables touched in an interrupts handler must be declared volatile.
TX and RX interrupts can occur in close succession, so the checks in the handler should take into account that both flags can be set at the same time. This is still no guarantee that you'd get meaningful counts, because a flag might be set just after you check it, then checked again and cleared in the HAL handler.
I don't know much about what goes on inside the HAL functions, post the contents of the SPI registers and the part number of the MCU.
You might as well try to do it without HAL, using the register interface as described in the reference manual, the outcome is more predictable.
2020-06-17 12:41 AM
it's an stm32F407