Stm32读adxl335B三个轴数据完整的代码
时间: 2023-12-03 12:02:20 浏览: 64
以下是STM32读取ADXL335B三轴数据的完整代码:
```
#include "stm32f4xx.h"
#define CS_HIGH() GPIO_SetBits(GPIOA, GPIO_Pin_4)
#define CS_LOW() GPIO_ResetBits(GPIOA, GPIO_Pin_4)
void SPI_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
SPI_InitTypeDef SPI_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource5, GPIO_AF_SPI1);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource6, GPIO_AF_SPI1);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource7, GPIO_AF_SPI1);
SPI_I2S_DeInit(SPI1);
SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex;
SPI_InitStructure.SPI_Mode = SPI_Mode_Master;
SPI_InitStructure.SPI_DataSize = SPI_DataSize_8b;
SPI_InitStructure.SPI_CPOL = SPI_CPOL_High;
SPI_InitStructure.SPI_CPHA = SPI_CPHA_2Edge;
SPI_InitStructure.SPI_NSS = SPI_NSS_Soft;
SPI_InitStructure.SPI_BaudRatePrescaler = SPI_BaudRatePrescaler_4;
SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB;
SPI_InitStructure.SPI_CRCPolynomial = 7;
SPI_Init(SPI1, &SPI_InitStructure);
SPI_Cmd(SPI1, ENABLE);
}
void ADXL335_Init(void)
{
CS_HIGH();
SPI_Configuration();
CS_LOW();
SPI_I2S_SendData(SPI1, 0x31);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);
SPI_I2S_ReceiveData(SPI1);
SPI_I2S_SendData(SPI1, 0x0B);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);
SPI_I2S_ReceiveData(SPI1);
CS_HIGH();
}
int ADXL335_ReadData(uint8_t reg)
{
uint8_t data[2];
CS_LOW();
SPI_I2S_SendData(SPI1, reg);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);
SPI_I2S_ReceiveData(SPI1);
SPI_I2S_SendData(SPI1, 0x00);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);
data[0] = SPI_I2S_ReceiveData(SPI1);
SPI_I2S_SendData(SPI1, 0x00);
while (SPI_I2S_GetFlagStatus(SPI1, SPI_I2S_FLAG_RXNE) == RESET);
data[1] = SPI_I2S_ReceiveData(SPI1);
CS_HIGH();
return ((data[1] << 8) | data[0]);
}
int main(void)
{
int x, y, z;
ADXL335_Init();
while (1)
{
x = ADXL335_ReadData(0x32);
y = ADXL335_ReadData(0x34);
z = ADXL335_ReadData(0x36);
printf("X = %d, Y = %d, Z = %d\n", x, y, z);
}
}
```
在主函数中,首先调用`ADXL335_Init()`函数进行ADXL335的初始化。然后进入一个无限循环中,不断读取ADXL335的X、Y、Z轴数据,并通过串口输出。`ADXL335_ReadData()`函数用于读取ADXL335的寄存器数据,需要传入寄存器地址作为参数。`SPI_Configuration()`函数用于配置STM32的SPI接口。`CS_HIGH()`和`CS_LOW()`函数用于控制SPI接口的片选信号。
阅读全文