User Manual
121
Code Explanation
#include <wiringPiI2C.h>:> // Include functions and method for the IIC protocol
#define DevAddr 0x53 // device address
struct acc_dat{ // a struct variable to store the value of x,y,and z
int x;
int y;
int z;
};
fd = wiringPiI2CSetup(DevAddr); // This initialises the I2C system with your given
device identifier
void adxl345_init(int fd){ // Initialize the device by i2c
wiringPiI2CWriteReg8(fd, 0x31, 0x0b); // These write an 8-bit data value into the
device register indicated.
wiringPiI2CWriteReg8(fd, 0x2d, 0x08); // Write 0x08 to the address (0x21) of the i2c
device
… …
}
struct acc_dat adxl345_read_xyz(int fd){ // a struct function, returning a struct value
char x0, y0, z0, x1, y1, z1;
struct acc_dat acc_xyz;
x0 = 0xff - wiringPiI2CReadReg8(fd, 0x32); // These read an 8- or 16-bit value from
the device register indicated.
x1 = 0xff - wiringPiI2CReadReg8(fd, 0x33); // Read an 8-bit data from the 0x33
register of the I2C device fd, assign to x1
y0 = 0xff - wiringPiI2CReadReg8(fd, 0x34);
y1 = 0xff - wiringPiI2CReadReg8(fd, 0x35);
z0 = 0xff - wiringPiI2CReadReg8(fd, 0x36);
z1 = 0xff - wiringPiI2CReadReg8(fd, 0x37);
printf(" x0 = %d ",x0);printf("x1 = %d \n",x1);
printf(" y0 = %d ",y0);printf("y1 = %d \n",y1);
printf(" z0 = %d ",z0);printf("z1 = %d \n",z1);
acc_xyz.x = (int)(x1 << 8) + (int)x0; // Assign values to members of the struct; the
value of x consists of x1 (high 8 bits) and x0 (low 8 bits).
acc_xyz.y = (int)(y1 << 8) + (int)y0;
acc_xyz.z = (int)(z1 << 8) + (int)z0;
if(acc_xyz.x > 32767){ // Set the value of x as no more than 0x7FFF
acc_xyz.x -= 65536;
}
SunFounder