AnsweredAssumed Answered

STM32F4 Discovery and accelerometer

Question asked by simonef on Sep 10, 2016
Latest reply on Nov 12, 2017 by Emrah Duatepe
Hi everybody,
I'm writing this post to ask if someone, please, can help me resolving a problem with the datas-reading from the accelerometer integrated in the STM32F4 Evaluation Board.
What I want to do it's simply to read the accelerations datas from the sensor, using the SPI interface. I've had a look at a lot of examples but I still don't know why my code doesn't work.
Here the main functions:

void WriteAccelerometer(SPI_HandleTypeDef SPI, uint8_t address, uint8_t data)
           HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_RESET); //CS --> Low
           HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_SET); //CS --> High

uint8_t ReadAccelerometer(SPI_HandleTypeDef SPI, uint8_t address, uint8_t data)
       address = address | 0x80;
       HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_RESET); //CS --> Low
          HAL_GPIO_WritePin(GPIOE, GPIO_PIN_3, GPIO_PIN_SET); //CS --> High
       return data;

Here the SPI configuration function:

static void MX_SPI1_Init(void)
     hspi1.Instance = SPI1;
  hspi1.Init.Mode = SPI_MODE_MASTER;
  hspi1.Init.Direction = SPI_DIRECTION_2LINES;
  hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
  hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
  hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
  hspi1.Init.NSS = SPI_NSS_SOFT;
  hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_16;
  hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
  hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
  hspi1.Init.CRCPolynomial = 10;
  if (HAL_SPI_Init(&hspi1) != HAL_OK)
     //WriteAccelerometer(hspi1,0x23,0xC9); //reset

I use the two functions reported in this post to configurate and read the accelerometer with this commands:

uint8_t config_address = 0x20;
uint8_t config_data = 0x27; 
uint8_t Address_ACCX = 0x29;
uint8_t Address_ACCY = 0x2B;
uint8_t Address_ACCZ = 0x2D;

WriteAccelerometer(hspi1,config_address,config_data); //config

// read data:
AccX = ReadAccelerometer(hspi1,Address_ACCX,AccX);
AccY = ReadAccelerometer(hspi1,Address_ACCY,AccY);
AccZ = ReadAccelerometer(hspi1,Address_ACCZ,AccZ);

Thank you in advance for the help..