[征文]STM32驱动ADXL345加速度成功 by Viola
这段时间比较忙,一直没来得及碰它们,前两天抽空用STM32驱动成功,发上代码与大家共享
void ADXL345_Init(void)
{
IWriteByte(ADXL345,0x2D,0x08);
IWriteByte(ADXL345,0x2C,0x0C);//Rate: 200Hz
IWriteByte(ADXL345,0x31,0x01);//Data Format: 8g right justified 128=1g
IWriteByte(ADXL345,0x2E,0xE4);//Int En: Data Rdy, Single Tap, Doulbe Tap,Free fall
IWriteByte(ADXL345,0x2A,0x01);//TAP_AXES:TAP_Z enable
IWriteByte(ADXL345,0x1D,0x20);//Tap Threshold: 2g(62.5mg/LSB) 62.5mg*32=2g
IWriteByte(ADXL345,0x28,0x09);//FreeFall Threshold: 600mg;
IWriteByte(ADXL345,0x29,0x14);//FreeFall Timing:100ms
IWriteByte(ADXL345,0x21,0x50);//Dur:50ms(625us/LSB)
IWriteByte(ADXL345,0x22,0x20);//Latent: 40ms(1.25ms/LSB)
IWriteByte(ADXL345,0x23,0xF0);//Window: 300ms
}
bool fADXL345_GetREGISTERData(ADXL345_TYPE* zdxl345)
{
u8 buff[1] = {0};
IReadStr(ADXL345,0x00,buff,1);//get device ID first
zdxl345->DevID = buff[0];
IReadStr(ADXL345,0x30,buff,1);//clear interrupt;
zdxl345->INT_Source = buff[0];
IReadStr(ADXL345,0x2C,buff,1);//clear interrupt;
zdxl345->RATE = buff[0];
if(zdxl345->DevID == 0xE5 && zdxl345->INT_Source == 0x02 && zdxl345->RATE == 0x0A)
{
return TRUE;//直接读取寄存器的值,与默认配置完全符合则证明模块上电正常,数据口读写正常
}
else
return FALSE;
}
void fADXL345_XYZdata(ADXL345_TYPE* zdxl345)
{
u8 buff[2] = {0};
fADXL345_GetREGISTERData(zdxl345);
ADXL345_Init();
while(1)
{
IReadStr(ADXL345,0x32,buff,2);//0x32(MSB) 0x33(LSB)
zdxl345->DataX = (buff[1] << 8) | buff[0];//LSB<<8+MSB
IReadStr(ADXL345,0x34,buff,2);
zdxl345->DataY = (buff[1] << 8) | buff[0];
IReadStr(ADXL345,0x36,buff,2);
zdxl345->DataZ = (buff[1] << 8) | buff[0];
}
}
这里我用的上模拟IIC,刚开始用硬件IIC,总是出现莫名其妙的问题,后来听说STM32的iic有问题,就改用模拟,一切正常。有空再用SPI来驱动下试试,欢迎大家交流~~~