Question
Working with STM32F103 and LSM6DSL Sensor. not getting data from LSM6DSL sensor. SPI Communication problem?
STM32F103 SPI Communication with LSM6DSLTR Sensor. not getting data from sensor.
Please go through my code and suggest me if any changes required in program
#include "main.h"
#include "timer.h"
#include "uart.h"
#include "gpio.h"
#include "spi.h"
void GPIOB_Init(void){
RCC->APB2ENR |= RCC_APB2ENR_IOPBEN;
RCC->APB2ENR |= RCC_APB2ENR_AFIOEN;
GPIOB->CRH = 0;
GPIOB->CRH |= (11U<<20); //PB13 (SCK) AF
GPIOB->CRH |= (11U<<28); //PB15 (MOSI) AF
GPIOB->CRH |= (1<<26); //PB14 (MISO) Input (floating)
GPIOB->CRH |= (3<<16); //PB12 used for CS, GPIO Output
GPIOB->BSRR |= GPIO_BSRR_BR12;
}
void SPI2_Init(void){
RCC->APB1ENR |= RCC_APB1ENR_SPI2EN; // Enable the clock for the SPI2 peripheral
SPI2->CR1 = 0x0000;
SPI2->CR2 = 0x0000;
SPI2->CR1 |= SPI_CR1_MSTR | SPI_CR1_SSI | SPI_CR1_SSM | SPI_CR1_CPHA | SPI_CR1_CPOL;
SPI2->CR1 |= (3<<3); //(SPI_CR1_BR_2 | SPI_CR1_BR_1);
SPI2->CR1 &= ~(1<<7); // LSBFIRST = 0, MSB first
SPI2->CR1 &= ~(SPI_CR1_RXONLY);
SPI2->CR1 &= ~(SPI_CR1_DFF);
SPI2->CR1 |= SPI_CR1_SPE;
}
void SPI2_Enable(void){
SPI2->CR1 |= SPI_CR1_SPE;
}
void SPI2_Disable(void){
SPI2->CR1 &= ~(SPI_CR1_SPE);
}
void CS_Enable(void){
GPIOB->BSRR |= GPIO_BSRR_BR12;//1<<(12+16);
}
void CS_Disable(void){
GPIOB->BSRR |= GPIO_BSRR_BS12; //(1<<12);
}
void SPI2_write(uint8_t data)
{
while(!(SPI2->SR & SPI_SR_TXE));
SPI2->DR = data;
while(!(SPI2->SR & SPI_SR_TXE));
while(!(SPI2->SR & SPI_SR_RXNE));
}
uint8_t SPI2_read(void)
{
uint8_t data;
while(!(SPI2->SR & SPI_SR_TXE));
while(!(SPI2->SR & SPI_SR_RXNE)){};
data = (uint8_t)SPI2->DR;
return data;
}
uint8_t LSM6DSLTR_read_reg(uint8_t reg_addr)
{
SPI2_Enable();
CS_Enable(); // CS is 0
SPI2_write(reg_addr | 0x80);
data = SPI2_read();
CS_Disable(); // pull the pin high
return data;
}
void LSM6DSLTR_Who_Am_I(void){
uint8_t data;
data = LSM6DSLTR_read_reg(0x0f);
Delay_ms(30);
UART1_TX("\n%x\n", data);
}
int main(){;
USART1_InItAF();
TIM4Config();
GPIOB_Init();
SPI2_Init();
SPI2_Enable();
CS_Enable();
Delay_ms(500);
while(1){
LSM6DSLTR_Who_Am_I();
Delay_ms(500);
}
}.