You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

STM32F4与LSM6DS3四线SPI通信异常问题求助

四线SPI读取LSM6DS3传感器数据异常问题排查

问题概述

使用STM32F411作为主机,通过四线SPI读取LSM6DS3传感器数据。根据 datasheet,四线SPI是传感器默认模式,因此未对传感器做额外配置直接尝试读取。读取"WHO_AM_I"寄存器时,出现响应脉冲过短无法识别的问题。

接线方式

4-wire SPI. Master - STM32F411.
LSM6DS3  to STM32F411
3v3      to  3.3V
GND      to  GND
SA0      to  PA6 - SPI1 MISO
CS       to  PA4 - GPIOA4
SDA      to  PA7 - SPI1 MOSI
SCL      to  PA5 - SPI1 SCK

异常现象

  • 发送0x8F(读位+"WHO_AM_I"寄存器地址0x0F)时,示波器和逻辑分析仪显示响应脉冲过短,无法正确读取预期值0x69(二进制01101001)
  • 读取"CTRL9_XL"寄存器时同样异常:预期值为00111000,实际读取到00110000,疑似脉冲被压缩导致数据丢失

配置代码

//SPI config:
void SpiConfig(void){
    RCC->APB2ENR |= (1 << 12);
    /////////////////////////////////////////////////// //////////
    SPI1->CR1 |= (1 << 0) | (1 << 1); //CPHA=1 CPOL=1
    SPI1->CR1 |= (1 << 2); //Master mod
    SPI1->CR1 |= (2 << 3); //010: fPCLK/8 BR[2:0] 5 MHz SPI CLK
    SPI1->CR1 &= ~(1 << 7); //LSBFIRST = 0 => MSB first, then LSB
    SPI1->CR1 |= (1 << 8 ) | (1 << 9); //High level SSI and SSM Software control enabled
    SPI1->CR1 &= ~(1 << 10); //RXONLY = 0 => Full duplex mode
    SPI1->CR1 &= ~(1 << 11); //8-bit
    SPI1->CR2 = 0;
}

//GPIO config:
void SpiGPIOConfig(void){
    RCC->AHB1ENR |= (1 << 0); //Enable RCC for GPIO_A
    GPIOA->MODER |= (2 << 10) | (2 << 12) | (2 << 14) | (1 << 8);
    //Alternative function for PA5/6/7 common output for PA4
    GPIOA->MODER &= ~(1 << 9); //Push-Pull for PA5/6/7/4 (default)
    GPIOA->OSPEEDR |= (3 << 10) | (3 << 12) | (3 << 14) | (3 << 8); //High speed for PA5/6/7/4
    GPIOA->AFR[0] |= (5 << 20) | (5 << 24) | (5 << 28); //AF5 (AFRL 0 - 7) on PA5/6/7
}

//Transmit:
void SPI_Transmit (uint8_t *data, int size){
    //1. Wait for the TXE bit to be set in the registration state
    int i = 0;
    while(i < size){
        while (!((SPI1->SR) & (1 << 1))){}; //Wait for the TXE bit to be set -> This indicates that the buffer is empty
        SPI1->DR = data[i]; //Load the data into the data register
        i++;
    }
    while(!((SPI1->SR) & (1 << 1))){}; //Wait for the TXE bit to be set -> This indicates that the buffer is empty
    while(((SPI1->SR) & (1 << 7))){}; //Wait for the BSY bit to clear -> This means that the SPIs are not busy with communications

    uint8_t temp = SPI1->DR;
    temperature = SPI1->SR;
}

//Main function:
uint8_t RxData[6];
uint8_t address = 0x8f;
while(1){
    CS_EN(); // pull the pin low
    SPI_Transmit (&address, 1); // send the address
    SPI_Receive (RxData, 1); // get 1 byte of data
    CS_DIS(); // pull the pin high

    Delay_ms(1);
}

注:原代码中address uint8_t = 0x8f;存在语法错误,已修正为uint8_t address = 0x8f;

内容的提问来源于stack exchange,提问作者Дмитро Мачковський

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:35:00