cancel
Showing results for 
Search instead for 
Did you mean: 

SPI Receive Only DMA

MarcTaekema
Associate

Hello,

I am using an STM32F401 board and trying to read a sensor using DMA. 
The sensor is a receive only sensor, i have tested with block SPI if the sensor works and it does. 

I am trying to read the sensor via DMA as it must be implemented with multiple SPI sensors, yet i can't get the buffer to read correctly? something like that. 
Launching the code with DMA in receive only causes the DMA interrupt, that would signal a succesfull read, to trigger before the data transfer is complete. I can see an SCLK from the MCU to the Sensor and some data that returns. Just not correct data. 

I have also tried using SPI Half Duplex Master, as this allows for prescaling the CLK output as well. Connecting the Sensor to the MOSI pin instead of the MISO and using the DMA TransmitReceive, while using dummy packages for the transmit. 
This causes the code to crash after a few succesfull DMA completions, yet the data is still incorrect even in the completed DMA requests. 

I have never used DMA before in projects, i might be making a trivial mistake. 
Help would be greatly appreciated and thanks for your time :)


/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "AksIMRLS.h"
#include "math.h"
#include "string.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define AksimRxTxBufferSize 1
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
uint16_t AksIMRLS_DMA_txBuffer[AksimRxTxBufferSize] = {0xFFFF};
uint16_t AksIMRLS_DMA_rxBuffer[AksimRxTxBufferSize];					//Same size empty buffer
volatile uint8_t AksIMRLS_DMA_TransferComplete = 0;						//Transfer Status Flag

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
SPI_HandleTypeDef hspi3;
DMA_HandleTypeDef hdma_spi3_rx;

UART_HandleTypeDef huart2;

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_DMA_Init(void);
static void MX_USART2_UART_Init(void);
static void MX_SPI3_Init(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
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_DMA_Init();
  MX_USART2_UART_Init();
  MX_SPI3_Init();
  /* USER CODE BEGIN 2 */

  //uint16_t AksIMRLS_ZeroPosition_Raw = AksIMRLS_ReceiveData(0) * 0.005493164f;
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  char DataBuffer[30];			//UART Data Buffer

  AksIMRLS_Select();		//Select Sensor
  HAL_Delay(1);			//250nS Delay Before fetching data, Replace with HW Timer in future (Currently 1,000,000 nS)
  while (1)
  {
	  /*
	  //Blocking SPI
	  float AksIMRLS_Position_Degrees = AksIMRLS_ReceiveData(&AksIMRLS_ZeroPosition_Raw);		//Get data from AksimRLS Sensor
	  int integerPart = (int)AksIMRLS_Position_Degrees;											//Extract Integer part
	  int decimalPart = (int)(fabs(AksIMRLS_Position_Degrees - integerPart) * 100);			//Extract decimal part
	  snprintf(DataBuffer, sizeof(DataBuffer), "%d.%02d\r\n", integerPart, decimalPart);		//Format Buffer
	  HAL_UART_Transmit(&huart2, (uint8_t*)DataBuffer, strlen(DataBuffer), 100);				//Send Buffer Via UART

	  HAL_Delay(1);
	*/

	  //DMA SPI
	  //SPI_Receive_DMA generates a Dummy Tx data itself to generate the Clock signal, so no need for transmit receive.
	  HAL_SPI_Receive_DMA(&hspi3, (uint8_t*)AksIMRLS_DMA_rxBuffer, sizeof(AksIMRLS_DMA_rxBuffer));
	  //HAL_SPI_TransmitReceive_DMA(&hspi3,(uint8_t*)AksIMRLS_DMA_txBuffer, (uint8_t*)AksIMRLS_DMA_rxBuffer, sizeof(AksIMRLS_DMA_rxBuffer));
	  while(!AksIMRLS_DMA_TransferComplete);
	  AksIMRLS_DMA_TransferComplete = 0;					//Reset Flag

	  float AksIMRLS_Position_Degrees = AksIMRLS_DMA_rxBuffer[0] * 0.005493164;
	  int integerPart = (int)AksIMRLS_Position_Degrees;											//Extract Integer part
	  int decimalPart = (int)(fabs(AksIMRLS_Position_Degrees - integerPart) * 100);				//Extract decimal part
	  snprintf(DataBuffer, sizeof(DataBuffer), "%d.%02d\r\n", integerPart, decimalPart);		//Format Buffer
	  HAL_UART_Transmit(&huart2, (uint8_t*)DataBuffer, strlen(DataBuffer), 100);				//Send Buffer Via UART
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  AksIMRLS_UnSelect();	//DeSelect Sensor
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 4;
  RCC_OscInitStruct.PLL.PLLN = 100;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief SPI3 Initialization Function
  * @PAram None
  * @retval None
  */
static void MX_SPI3_Init(void)
{

  /* USER CODE BEGIN SPI3_Init 0 */

  /* USER CODE END SPI3_Init 0 */

  /* USER CODE BEGIN SPI3_Init 1 */

  /* USER CODE END SPI3_Init 1 */
  /* SPI3 parameter configuration*/
  hspi3.Instance = SPI3;
  hspi3.Init.Mode = SPI_MODE_MASTER;
  hspi3.Init.Direction = SPI_DIRECTION_2LINES_RXONLY;
  hspi3.Init.DataSize = SPI_DATASIZE_16BIT;
  hspi3.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi3.Init.CLKPhase = SPI_PHASE_2EDGE;
  hspi3.Init.NSS = SPI_NSS_SOFT;
  hspi3.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_32;
  hspi3.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi3.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi3.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
  hspi3.Init.CRCPolynomial = 10;
  if (HAL_SPI_Init(&hspi3) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN SPI3_Init 2 */
  __HAL_RCC_SPI3_CLK_ENABLE(); 					//Enable Clock
  /* USER CODE END SPI3_Init 2 */

}

/**
  * @brief USART2 Initialization Function
  * @PAram None
  * @retval None
  */
static void MX_USART2_UART_Init(void)
{

  /* USER CODE BEGIN USART2_Init 0 */

  /* USER CODE END USART2_Init 0 */

  /* USER CODE BEGIN USART2_Init 1 */

  /* USER CODE END USART2_Init 1 */
  huart2.Instance = USART2;
  huart2.Init.BaudRate = 115200;
  huart2.Init.WordLength = UART_WORDLENGTH_8B;
  huart2.Init.StopBits = UART_STOPBITS_1;
  huart2.Init.Parity = UART_PARITY_NONE;
  huart2.Init.Mode = UART_MODE_TX_RX;
  huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart2.Init.OverSampling = UART_OVERSAMPLING_16;
  if (HAL_UART_Init(&huart2) != HAL_OK)
  {
    Error_Handler();
  }
  /* USER CODE BEGIN USART2_Init 2 */

  /* USER CODE END USART2_Init 2 */

}

/**
  * Enable DMA controller clock
  */
static void MX_DMA_Init(void)
{

  /* DMA controller clock enable */
  __HAL_RCC_DMA1_CLK_ENABLE();

  /* DMA interrupt init */
  /* DMA1_Stream0_IRQn interrupt configuration */
  HAL_NVIC_SetPriority(DMA1_Stream0_IRQn, 0, 0);
  HAL_NVIC_EnableIRQ(DMA1_Stream0_IRQn);

}

/**
  * @brief GPIO Initialization Function
  * @PAram None
  * @retval None
  */
static void MX_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};
/* USER CODE BEGIN MX_GPIO_Init_1 */
/* USER CODE END MX_GPIO_Init_1 */

  /* GPIO Ports Clock Enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();
  __HAL_RCC_GPIOH_CLK_ENABLE();
  __HAL_RCC_GPIOA_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(LD2_GPIO_Port, LD2_Pin, GPIO_PIN_RESET);

  /*Configure GPIO pin Output Level */
  HAL_GPIO_WritePin(SPI3_CS_GPIO_Port, SPI3_CS_Pin, GPIO_PIN_SET);

  /*Configure GPIO pin : B1_Pin */
  GPIO_InitStruct.Pin = B1_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : LD2_Pin */
  GPIO_InitStruct.Pin = LD2_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(LD2_GPIO_Port, &GPIO_InitStruct);

  /*Configure GPIO pin : SPI3_CS_Pin */
  GPIO_InitStruct.Pin = SPI3_CS_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_PULLUP;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
  HAL_GPIO_Init(SPI3_CS_GPIO_Port, &GPIO_InitStruct);

/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}

/* USER CODE BEGIN 4 */

void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi)
{
	//Receive Only master mode DMA Handler.
	if(hspi -> Instance == SPI3){
		AksIMRLS_DMA_TransferComplete = 1;
	}
}ws
void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi)
{
	//Receive Only master mode DMA Handler.
	if(hspi -> Instance == SPI3){
		AksIMRLS_DMA_TransferComplete = 1;
	}
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @PAram  file: pointer to the source file name
  * @PAram  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

 

2 REPLIES 2
TDK
Guru

> I can see an SCLK from the MCU to the Sensor and some data that returns. Just not correct data. 

If the sensor returns incorrect data, how is the MCU at fault? What about the data is incorrect?

If you feel a post has answered your question, please click "Accept as Solution".

Okay so i may have explained that poorly, The sensor returns incorrect data because the SCLK is stopped before the sensor can return a full 16-bit signal. So it appears as incorrect on the scope. Whereas using a blocking SPI function the data returns perfectly fine as it just waits for the SPI to complete before executing other code. 

So it seems that the DMA transfercomplete bit in the register flip sooner than a data packet is retrieved.