Is my ASM330LHH imu sensor spi code correct?
I want to read acc and gyro data from my ASM330LHH sensor with spi communication, but I can't try the code because I don't have a sensor at the moment, can you take a look at the code, is there anything wrong or missing?
(I selected the SPI_CS pin as PA4 and set it as in the screenshot, is it correct?)
(Do I need to write BSP_SPI1_Init(); in main function?)
(Should I use the ASM330LHH_Init(&imu); function last after scale and enable functions?)
/* 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 "stm32f429i_disc1_bus.h" // BSP I2C fonksiyonları için gerekli
#include "stdio.h"
#include "string.h"
#include "asm330lhh.h" // X-CUBE-MEMS1 paketi içerisindeki ASM330LHH sürücü dosyaları
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* IMU Nesneleri */
ASM330LHH_Object_t imu;
ASM330LHH_IO_t io_ctx;
ASM330LHH_Axes_t accel, gyro;
char buffer[100]; // UART üzerinden veri gönderimi için
/* Düşük Geçiren Filtre Değişkenleri */
float ax_f = 0.0f, ay_f = 0.0f, az_f = 0.0f;
float gx_f = 0.0f, gy_f = 0.0f, gz_f = 0.0f;
float alpha = 0.1f; // 0.0 - 1.0 arası, yeni verinin ağırlığı
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
UART_HandleTypeDef huart1;
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_USART1_UART_Init(void);
/* USER CODE BEGIN PFP */
void UART_SendData(const char *data);
void IMU_SPI_Init(void);
void IMU_ReadData(void);
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
int32_t BSP_SPI1_WriteReg(uint16_t Address, uint16_t Reg, uint8_t *pData, uint16_t len)
{
uint8_t tx_buffer[len + 1];
uint8_t rx_buffer[len + 1];
// İlk byte yazma komutu: (Register adresi & 0x7F)
tx_buffer[0] = (uint8_t)(Reg & 0x7F);
memcpy(&tx_buffer[1], pData, len);
HAL_GPIO_WritePin(SPI_CS_GPIO_Port, SPI_CS_Pin, GPIO_PIN_RESET);
int32_t status = BSP_SPI1_SendRecv(tx_buffer, rx_buffer, len + 1);
HAL_GPIO_WritePin(SPI_CS_GPIO_Port, SPI_CS_Pin, GPIO_PIN_SET);
return status;
}
int32_t BSP_SPI1_ReadReg(uint16_t Address, uint16_t Reg, uint8_t *pData, uint16_t len)
{
uint8_t tx_buffer[len + 1];
uint8_t rx_buffer[len + 1];
// İlk byte okuma komutu: (Register adresi | 0x80)
tx_buffer[0] = (uint8_t)(Reg | 0x80);
memset(&tx_buffer[1], 0xFF, len); // Dummy byte gönderilir
HAL_GPIO_WritePin(SPI_CS_GPIO_Port, SPI_CS_Pin, GPIO_PIN_RESET);
int32_t status = BSP_SPI1_SendRecv(tx_buffer, rx_buffer, len + 1);
HAL_GPIO_WritePin(SPI_CS_GPIO_Port, SPI_CS_Pin, GPIO_PIN_SET);
memcpy(pData, &rx_buffer[1], len);
return status;
}
/* 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_USART1_UART_Init();
/* USER CODE BEGIN 2 */
BSP_SPI1_Init(); // Is that necessary?
IMU_SPI_Init();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
IMU_ReadData();
HAL_Delay(10); // 100 Hz veri okuma hızı için 10ms bekle
}
/* 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 = 180;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
RCC_OscInitStruct.PLL.PLLQ = 3;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Activate the Over-Drive mode
*/
if (HAL_PWREx_EnableOverDrive() != 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_DIV4;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
{
Error_Handler();
}
}
/**
* @brief USART1 Initialization Function
* None
* @retval None
*/
static void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
/**
* @brief GPIO Initialization Function
* 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_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(SPI_CS_GPIO_Port, SPI_CS_Pin, GPIO_PIN_SET);
/*Configure GPIO pin : SPI_CS_Pin */
GPIO_InitStruct.Pin = SPI_CS_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(SPI_CS_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN MX_GPIO_Init_2 */
/* USER CODE END MX_GPIO_Init_2 */
}
/* USER CODE BEGIN 4 */
void UART_SendData(const char *data) {
HAL_UART_Transmit(&huart1, (uint8_t*)data, strlen(data), 100);
}
void IMU_SPI_Init(void) {
io_ctx.BusType = ASM330LHH_SPI_4WIRES_BUS;
io_ctx.Init = BSP_SPI1_Init;
io_ctx.DeInit = BSP_SPI1_DeInit;
io_ctx.ReadReg = BSP_SPI1_ReadReg;
io_ctx.WriteReg = BSP_SPI1_WriteReg;
io_ctx.GetTick = BSP_GetTick;
// SPI kullanımında sensör adresi gerekmiyor, CS pini kontrol edilir.
io_ctx.Address = 0; // SPI'de adres 0 olarak bırakılır
ASM330LHH_RegisterBusIO(&imu, &io_ctx);
uint8_t whoamI = 0;
ASM330LHH_ReadID(&imu, &whoamI);
if (whoamI != ASM330LHH_ID) {
UART_SendData("IMU Error: Sensor not found!\r\n");
Error_Handler();
}
ASM330LHH_Init(&imu);
ASM330LHH_ACC_Enable(&imu);
ASM330LHH_GYRO_Enable(&imu);
ASM330LHH_ACC_SetFullScale(&imu, 4); // ±4g
ASM330LHH_GYRO_SetFullScale(&imu, 2000); // ±2000 dps
ASM330LHH_ACC_SetOutputDataRate(&imu, 416.0f);
ASM330LHH_GYRO_SetOutputDataRate(&imu, 416.0f);
UART_SendData("IMU Initialized via SPI\r\n");
}
/* IMU Verilerini Okuma, Dönüştürme ve Filtreleme Fonksiyonu */
void IMU_ReadData(void) {
ASM330LHH_ACC_GetAxes(&imu, &accel);
ASM330LHH_GYRO_GetAxes(&imu, &gyro);
/* İvmeölçer verisini mg'den m/s²'ye çevirme (1 mg ≈ 0.00980665 m/s²) */
float ax = accel.x * 0.00980665f;
float ay = accel.y * 0.00980665f;
float az = accel.z * 0.00980665f;
/* Jiroskop verisini mdps'den dps'ye çevirme (1000 mdps = 1 dps) */
float gx = gyro.x * 0.001f;
float gy = gyro.y * 0.001f;
float gz = gyro.z * 0.001f;
/* Düşük geçiren filtre uygulaması */
ax_f = ax_f * (1.0f - alpha) + ax * alpha;
ay_f = ay_f * (1.0f - alpha) + ay * alpha;
az_f = az_f * (1.0f - alpha) + az * alpha;
gx_f = gx_f * (1.0f - alpha) + gx * alpha;
gy_f = gy_f * (1.0f - alpha) + gy * alpha;
gz_f = gz_f * (1.0f - alpha) + gz * alpha;
/* Formatlı veriyi UART üzerinden gönder */
sprintf(buffer, "AX:%.2f AY:%.2f AZ:%.2f | GX:%.2f GY:%.2f GZ:%.2f\r\n",
ax_f, ay_f, az_f, gx_f, gy_f, gz_f);
UART_SendData(buffer);
}
/* 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.
* file: pointer to the source file name
* 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 */
