Arduino I2C + 三轴加速度计ADXL345
ADXL345是ADI公司生产的三轴数字加速度计芯片,与ST的LIS3DH功能接近。主要特性有:
- 工作电压:2.0 ~ 3.6V
- 功耗:待机功耗0.1μA;工作时与数据输出频率(ODR)有关,如ODR<10 Hz时30μA
- 接口:I2C;三线/四线制SPI
- 分辨率:可选择,最大13-bit
- 内置FIFO
- single tap/double tap检测
- 自由落体检测
- 两个可编程中断输出脚
- 封装:3 x 5 x 1 mm LGA
管脚定义
与Arduino的连接
用工作于3.3V/8MHz版本的Arduino Pro Mini进行调试。管脚定义、连接方法与调试LIS3DH时类似。采用I2C接口进行通讯,未利用FIFO和INT1、INT2中断引脚。
ADXL345 Pro Mini (3.3V)
VDD <------> 3.3V
GND <------> GND
SCL <------> A5 (SCL)
SDA <------> A4 (SDA)
功能调试
1. 操作方法亦和LIS3DH类似。但ADXL345似乎没有与LIS3DH的STATUS_REG寄存器,而是设定DATA_READY中断,然后利用INT_SOURCE寄存器判断是否有中断事件发生,从而判断是否有新的测量值。
2. 留意设置的ODR频率不要超出I2C总线的数据读取速率。如Arduino的I2C总线时钟频率为100kHz,则可设置的最大ODR为200Hz。
测试代码
1 /* 2 Measurement of acceleration values using motion sensor ADXL345 3 */ 4 #include <Wire.h> 5 6 #define ADDRESS_ADXL345 0x53 7 #define DATA_FORMAT 0x31 8 #define BW_RATE 0x2C 9 #define POWER_CTL 0x2D 10 #define INT_ENABLE 0x2E 11 #define INT_SOURCE 0x30 12 #define DATAX0 0x32 13 14 byte buffer[6]; 15 byte intSource; 16 17 boolean ready = false; 18 19 int outX, outY, outZ; 20 float xVal, yVal, zVal; 21 22 void setup() 23 { 24 Wire.begin(); 25 Serial.begin(9600); 26 27 delay(2); 28 29 // set scale = +/- 2g, 13-bit mode 30 Wire.beginTransmission(ADDRESS_ADXL345); 31 Wire.write(DATA_FORMAT); 32 Wire.write(0x08); 33 Wire.endTransmission(); 34 // set ODR = 1.56 Hz 35 Wire.beginTransmission(ADDRESS_ADXL345); 36 Wire.write(BW_RATE); 37 Wire.write(0x04); 38 Wire.endTransmission(); 39 40 // start measurement 41 Wire.beginTransmission(ADDRESS_ADXL345); 42 Wire.write(POWER_CTL); 43 Wire.write(0x08); 44 Wire.endTransmission(); 45 46 // enable DATA_READY interrupt 47 Wire.beginTransmission(ADDRESS_ADXL345); 48 Wire.write(INT_ENABLE); 49 Wire.write(0x80); 50 Wire.endTransmission(); 51 } 52 53 void loop() 54 { 55 // check data ready 56 while(ready == false) 57 { 58 Wire.beginTransmission(ADDRESS_ADXL345); 59 Wire.write(INT_SOURCE); 60 Wire.endTransmission(); 61 Wire.requestFrom(ADDRESS_ADXL345, 1); 62 if (Wire.available() >= 1) 63 { 64 intSource = Wire.read(); 65 } 66 if (bitRead(intSource, 7) == 1) //new data available 67 { 68 ready = true; 69 } 70 } 71 if (bitRead(intSource, 0) == 1) 72 { 73 Serial.println("Some data have been overwritten."); 74 } 75 76 //read the result 77 Wire.beginTransmission(ADDRESS_ADXL345); 78 Wire.write(DATAX0); //read multiple bytes 79 Wire.endTransmission(); 80 Wire.requestFrom(ADDRESS_ADXL345, 6); 81 if (Wire.available() >= 6) 82 { 83 for (int i = 0; i < 6; i++) 84 { 85 buffer[i] = Wire.read(); 86 } 87 } 88 89 //calculation 90 outX = (buffer[1] << 8) | buffer[0]; 91 outY = (buffer[3] << 8) | buffer[2]; 92 outZ = (buffer[5] << 8) | buffer[4]; 93 xVal = outX *3.9; 94 yVal = outY *3.9; 95 zVal = outZ *3.9; 96 97 Serial.print("outX: "); Serial.print(xVal); Serial.print(" "); 98 Serial.print("outY: "); Serial.print(yVal); Serial.print(" "); 99 Serial.print("outZ: "); Serial.println(zVal); 100 101 ready = false; 102 }
ODR设定为1.56Hz,通过串口打印三个维度的加速度值,单位为mg。