做一个测试ADXL345采集数据的实验,ADXL345通过IO模拟SPI连接单片机,单片机通过串口连接PC并显示读出的加速度值,可是读出任何寄存器的的数据不变只是66 或者76,请求帮助,下边是程序:
#include
#include
#define SDO P0^2;
sbit SDI=P0^3;
sbit CS=P0^4;
sbit SCLK=P0^5;
#define uchar unsigned char
#define uint unsigned int
int temp=0;
uint i;
uchar strm;
void SPI_Wrt(uint addr,uint dat);
void SPI_SWrt(uint spib);
int SPI_Read(uint addr);
void delay(uint z);
uint zh,zl,flag;
void main()
{
SPI_Wrt(0x2D,0x28); //ADXL初始化
SPI_Wrt(0x31,0x0B); //数据通信格式;设置为自检功能禁用,4线制Spi接口,低电平中断输出,13位全分辨率,输出数据右对齐,16g量程
SPI_Wrt(0x1E,0x00); //X轴误差补偿; (15.6mg/LSB)
SPI_Wrt(0x1F,0x00); //Y轴误差补偿; (15.6mg/LSB)
SPI_Wrt(0x20,0x05); //Z轴误差补偿; (15.6mg/LSB)
SPI_Wrt(0x21,0x00); //禁用敲击延迟
SPI_Wrt(0x22,0x00);
SPI_Wrt(0x23,0x00);
SPI_Wrt(0x24,0x01); //保存检测活动阀值; (62.5mg/LSB)
SPI_Wrt(0x25,0x01); //保存检测静止阀值; (62.5mg/LSB)
SPI_Wrt(0x26,0x2B); //检测静止时间阀值; (1s/LSB)
SPI_Wrt(0x27,0x77); //ACT_INACT_CTL;
SPI_Wrt(0x2C,0x08); //设置采样率为25Hz
//SPI_Wrt(0x2D,0x28); //设置为正常工作模式
SPI_Wrt(0x2E,0x00); //中断功能设定,不使用中断
SPI_Wrt(0x2f,0x00);
SPI_Wrt(0x38,0x9f);
TMOD=0x20; //串口初始化
TH1=0xfA;
TL1=0xfA;
TR1=1;
REN=1;
SM0=0;
SM1=1;
EA=1;
//ES=0;
flag=0;
delay(100);
while(1)
{
zl=SPI_Read(0x35);
delay(100);
SBUF=zl;
delay(100);
}
}
void SPI_Wrt(uint addr,uint dat) //ADXL写数据//地址格式:0xFF 数据格式:0xFF
{
CS=1;
SCLK=1;
delay(50);
CS=0;
SPI_SWrt(addr);
delay(50);
SPI_SWrt(dat);
delay(50);
CS=1;
}
int SPI_Read(uint addr) //ADXL读数据//地址格式:0xFF 数据格式:0xFF
{
CS=1;
SCLK=1;
delay(10);
CS=0;
addr|=0x80;
SPI_SWrt(addr);
delay(100);
strm=0x00;
for(i=0;i<8;i++)
{
SCLK=0;
strm=strm+SDO;
strm=strm<<1;
SCLK=1;
}
delay(10);
CS=1;
return strm;
}
void SPI_SWrt(uint spib)
{
for(i=0;i<8;i++)
{
SCLK=0;
if((spib 0x80)==0x80)SDI=1;
else SDI=0;
SCLK=1;
spib=(spib<<1);
}
}
void delay(uint z)//延迟函数
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);