STM32 SPI 与 HAL 通信
Posted
技术标签:
【中文标题】STM32 SPI 与 HAL 通信【英文标题】:STM32 SPI communication with HAL 【发布时间】:2021-08-27 13:34:29 【问题描述】:我刚开始对 STM32 进行编程,并使用 CubeMX 生成了一个代码,用于与陀螺仪 (L3GD20) 进行 SPI 通信 我对 HAL_SPI 命令有疑问。
我首先尝试读取返回良好响应 (0xD4) 的 WHO_AM_I
寄存器
然后我尝试对CTRL_REG1
register 做同样的事情,返回 (0x07) 仍然很好。
但如果我尝试一个接一个地获取它们,HAL_SPI_Receive
会继续发送代码的第一个HAL_SPI_Transmit
的数据...
试图给它其他缓冲区,但仍然没有工作。
这是我感兴趣的代码部分:
uint8_t txData[8],rxData[8]; //Buffers for the first read.
uint8_t rBuffer[8]; //Buffer for the second read.
/*...............................................................
*...............................................................
*...............................................................
*/...............................................................
txData[0] = ADDR_WHO_AM_I | 0x80;
HAL_SPI_Transmit(&hspi2, txData, 1, HAL_MAX_DELAY);
HAL_SPI_Receive(&hspi2, rxData, 1, HAL_MAX_DELAY); //Returns the right value
HAL_Delay(1000);
txData[0] = ADDR_CTRL_REG1 | 0x80;
HAL_Delay(500);
HAL_SPI_Transmit(&hspi2, txData, 1, HAL_MAX_DELAY);
HAL_SPI_Receive(&hspi2, rBuffer, 1, HAL_MAX_DELAY); //Returns the same value...
HAL_Delay(1000);
PS:如果可能的话,我还想了解更多关于HAL_SPI_TransmitReceive
的信息,我应该如何使用它来执行相同的任务? (从不同的寄存器读取 1 个字节)。
还有完整的代码:
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
// Gyro Definitions
#define ADDR_WHO_AM_I 0x0f
#define ADDR_CTRL_REG1 0x20
#define ADDR_CTRL_REG2 0x21
#define ADDR_CTRL_REG3 0x22
#define ADDR_CTRL_REG4 0x23
#define ADDR_CTRL_REG5 0x24
#define ADDR_OUT_TEMP 0x26
#define ADDR_STATUS_REG 0x27
#define ADDR_OUT_X_L 0x28
#define ADDR_OUT_X_H 0x29
#define ADDR_OUT_Y_L 0x2A
#define ADDR_OUT_Y_H 0x2B
#define ADDR_OUT_Z_L 0x2C
#define ADDR_OUT_Z_H 0x2D
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
I2C_HandleTypeDef hi2c3;
SD_HandleTypeDef hsd1;
SPI_HandleTypeDef hspi2;
/* USER CODE BEGIN PV */
HAL_SD_CardInfoTypeDef pCardInfo;
char datar[1024];
HAL_StatusTypeDef retstat;
//HAL_MMC_CardInfoTypeDef pCardInfo;
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_SDMMC1_SD_Init(void);
static void MX_I2C3_Init(void);
static void MX_SPI2_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 */
int ret;
uint8_t txData[8],rxData[8]; //Buffers for the first read.
uint8_t rBuffer[8]; //Buffer for the second read.
/* 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_SDMMC1_SD_Init();
MX_I2C3_Init();
MX_SPI2_Init();
/* USER CODE BEGIN 2 */
txData[0] = ADDR_WHO_AM_I | 0x80;
HAL_SPI_Transmit(&hspi2, txData, 1, HAL_MAX_DELAY);
HAL_SPI_Receive(&hspi2, rxData, 1, HAL_MAX_DELAY);
HAL_Delay(1000);
txData[0] = ADDR_CTRL_REG1 | 0x80;
HAL_Delay(500);
HAL_SPI_Transmit(&hspi2, txData, 1, HAL_MAX_DELAY);
HAL_SPI_Receive(&hspi2, rBuffer, 1, HAL_MAX_DELAY);
HAL_Delay(1000);
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
/* USER CODE END 3 */
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
RCC_OscInitTypeDef RCC_OscInitStruct = 0;
RCC_ClkInitTypeDef RCC_ClkInitStruct = 0;
RCC_PeriphCLKInitTypeDef PeriphClkInit = 0;
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 1;
RCC_OscInitStruct.PLL.PLLN = 10;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7;
RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV4;
RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2;
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_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
Error_Handler();
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_I2C3|RCC_PERIPHCLK_SDMMC1;
PeriphClkInit.I2c3ClockSelection = RCC_I2C3CLKSOURCE_PCLK1;
PeriphClkInit.Sdmmc1ClockSelection = RCC_SDMMC1CLKSOURCE_PLL;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
Error_Handler();
/** Configure the main internal regulator output voltage
*/
if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
Error_Handler();
/**
* @brief I2C3 Initialization Function
* @param None
* @retval None
*/
static void MX_I2C3_Init(void)
/* USER CODE BEGIN I2C3_Init 0 */
/* USER CODE END I2C3_Init 0 */
/* USER CODE BEGIN I2C3_Init 1 */
/* USER CODE END I2C3_Init 1 */
hi2c3.Instance = I2C3;
hi2c3.Init.Timing = 0x10909CEC;
hi2c3.Init.OwnAddress1 = 0;
hi2c3.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c3.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c3.Init.OwnAddress2 = 0;
hi2c3.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
hi2c3.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c3.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c3) != HAL_OK)
Error_Handler();
/** Configure Analogue filter
*/
if (HAL_I2CEx_ConfigAnalogFilter(&hi2c3, I2C_ANALOGFILTER_ENABLE) != HAL_OK)
Error_Handler();
/** Configure Digital filter
*/
if (HAL_I2CEx_ConfigDigitalFilter(&hi2c3, 0) != HAL_OK)
Error_Handler();
/* USER CODE BEGIN I2C3_Init 2 */
/* USER CODE END I2C3_Init 2 */
/**
* @brief SDMMC1 Initialization Function
* @param None
* @retval None
*/
static void MX_SDMMC1_SD_Init(void)
/* USER CODE BEGIN SDMMC1_Init 0 */
/* USER CODE END SDMMC1_Init 0 */
/* USER CODE BEGIN SDMMC1_Init 1 */
/* USER CODE END SDMMC1_Init 1 */
hsd1.Instance = SDMMC1;
hsd1.Init.ClockEdge = SDMMC_CLOCK_EDGE_RISING;
hsd1.Init.ClockBypass = SDMMC_CLOCK_BYPASS_DISABLE;
hsd1.Init.ClockPowerSave = SDMMC_CLOCK_POWER_SAVE_DISABLE;
hsd1.Init.BusWide = SDMMC_BUS_WIDE_1B;
hsd1.Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_ENABLE;
hsd1.Init.ClockDiv = 0;
if (HAL_SD_Init(&hsd1) != HAL_OK)
Error_Handler();
if (HAL_SD_ConfigWideBusOperation(&hsd1, SDMMC_BUS_WIDE_4B) != HAL_OK)
Error_Handler();
/* USER CODE BEGIN SDMMC1_Init 2 */
//HAL_StatusTypeDef HAL_MMC_GetCardInfo(MMC_HandleTypeDef *hmmc, HAL_MMC_CardInfoTypeDef *pCardInfo)
/* USER CODE END SDMMC1_Init 2 */
/**
* @brief SPI2 Initialization Function
* @param None
* @retval None
*/
static void MX_SPI2_Init(void)
/* USER CODE BEGIN SPI2_Init 0 */
/* USER CODE END SPI2_Init 0 */
/* USER CODE BEGIN SPI2_Init 1 */
/* USER CODE END SPI2_Init 1 */
/* SPI2 parameter configuration*/
hspi2.Instance = SPI2;
hspi2.Init.Mode = SPI_MODE_MASTER;
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_OUTPUT;
hspi2.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_8;
hspi2.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi2.Init.TIMode = SPI_TIMODE_DISABLE;
hspi2.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi2.Init.CRCPolynomial = 7;
hspi2.Init.CRCLength = SPI_CRC_LENGTH_DATASIZE;
hspi2.Init.NSSPMode = SPI_NSS_PULSE_DISABLE;
if (HAL_SPI_Init(&hspi2) != HAL_OK)
Error_Handler();
/* USER CODE BEGIN SPI2_Init 2 */
/* USER CODE END SPI2_Init 2 */
/**
* @brief GPIO Initialization Function
* @param None
* @retval None
*/
static void MX_GPIO_Init(void)
GPIO_InitTypeDef GPIO_InitStruct = 0;
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOE_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOE, GPIO_PIN_1|GPIO_PIN_0, GPIO_PIN_RESET);
/*Configure GPIO pins : PE1 PE0 */
GPIO_InitStruct.Pin = GPIO_PIN_1|GPIO_PIN_0;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOE, &GPIO_InitStruct);
/* USER CODE BEGIN 4 */
/* 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 */
/* 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,
tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
#endif /* USE_FULL_ASSERT */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
【问题讨论】:
设备接收和发送有意义吗?这就是阅读该设备的数据表的全部内容。普通SPI收发,同时发送和发送,全双工。 【参考方案1】:我无法解释您为单独的 HAL_SPI_Transmit() 和 HAL_SPI_Receive() 调用描述的行为。但无论如何,您应该使用 HAL_SPI_TransmitReceive()。这是一个例子。
HAL_StatusTypeDef ReadRegister(uint8_t addr, uint8_t *byte)
HAL_StatusTypeDef hal_status;
uint8_t tx_data[2];
uint8_t rx_data[2];
tx_data[0] = addr | 0x80; // read operation
tx_data[1] = 0; // dummy byte for response
hal_status = HAL_SPI_TransmitReceive(&hspi2, tx_data, rx_data, 2, SPI_TIMEOUT);
if (hal_status == HAL_OK)
*byte = rx_data[1]; // response is in the second byte
return hal_status;
主 SPI 控制器时钟输出字节,并且在每个字节期间主从发送和接收。对于第一个字节,主机发送寄存器 addr 而从机发送一个虚拟字节,因为从机还不知道您要读取的寄存器是什么。 (一些从设备在第一个字节中发送一个状态。)对于第二个字节,主设备发送一个虚拟字节,以便生成更多时钟,从设备可以响应。在第一个字节期间接收到寄存器地址后,从机知道在第二个字节期间要发送哪个寄存器值。请注意,在示例代码中,您感兴趣的接收字节是响应缓冲区的第二个字节。
【讨论】:
【参考方案2】:由于HAL_SPI_Receive
已经在使用HAL_SPI_TransmitReceive
(github stm32f4 spi driver) 发送虚拟数据来生成时钟,因此您可以使用该事实并放弃HAL_SPI_Transmit
,并像这样使用接收函数:
rxData[0] = ADDR_WHO_AM_I | 0x80;
HAL_SPI_Receive(&hspi2, rxData, 1, HAL_MAX_DELAY);
请注意,我们使用 rxData 提供地址和操作,但它会被读取的数据有效地覆盖。
或者你可以简单地使用HAL_SPI_TransmitReceive
:
txData[0] = ADDR_WHO_AM_I | 0x80;
HAL_SPI_TransmitReceive(&hspi2, txData, rxData, 1, HAL_MAX_DELAY);
HAL_Delay(500);
txData[0] = ADDR_CTRL_REG1 | 0x80;
HAL_SPI_TransmitReceive(&hspi2, txData, rxData, 1, HAL_MAX_DELAY);
【讨论】:
Size = 1 是不够的。设备可能会在第一个字节中发送虚拟或状态数据,因为它在收到第一个字节中的寄存器地址之前不知道要返回哪个寄存器值。所以读取寄存器值需要size = 2。 HAL_SPI_TransmitReceive函数的接收部分发生在发送第一个字节之后,由于这里的MCU是主控,并且数据手册明确指出从第9个时钟脉冲开始从传感器输出的数据被锁存,而且我们只读取 1 个字节的数据,然后 1 个字节的大小就足够了,请注意 HAL_SPI_TransmitReceive 中的 size 参数并不意味着 sizeof(tx+rx) ,两者都相同:所以模式和地址的 1 个字节(tx ) 和 1 个字节用于从属数据 (rx),请查看 github 链接的第 1185 和 1188 行。 看一下从第 1264 行开始的 while 循环。循环每次通过循环都发送和接收一个字节(并递减两个计数器)。 SPI 是全双工的,每个循环只有 8 个时钟脉冲。您必须传输第二个虚拟字节才能获得第 9 到第 16 个时钟脉冲。以上是关于STM32 SPI 与 HAL 通信的主要内容,如果未能解决你的问题,请参考以下文章