#include <18f4550.h>
#fuses HS,NOWDT,NOPROTECT,NOLVP
#use delay(clock=4000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, parity=N, bits=8, errors)
#use i2c(master, sda=PIN_B0, scl=PIN_B1)
void main()
{
unsigned int whoami;
unsigned int conf1;
unsigned int conf2;
unsigned int raw_accel[6]; //to store raw acceleration data.
int i = 7;
//long int x_accel;
int16 x_accel;
int16 y_accel;
int16 z_accel;
//The G's
float x_g;
float y_g;
float z_g;
delay_ms(250); //Give things time to warm up
//Now we're going to enable the accelerometer.
i2c_start();
i2c_write(0x32);
i2c_write(0x20); //CTRL_REG1
i = i2c_write(0x57);
i2c_stop();
i2c_start();
i2c_write(0x32);
i2c_write(0x23); //CTRL_REG4
i = i2c_write(0x00);
i2c_stop();
printf("Accelerometer should be enabled... %u",i);
//check to see if communications are ok. (Read WHOAMI)
i2c_start();
i2c_write(0x32);
i2c_write(0x23); //WHOAMI---ctrlreg4
i2c_start();
i2c_write(0x33);
whoami = i2c_read();
i2c_stop();
printf("\r\nWHOAMI = %3u \r\n",whoami); //print it out on the serial link.
//If WHOAMI = 58 (3A) we're good. we can talk to accelerometer.
i2c_start();
i2c_write(0x32);
i2c_write(0x20); //CTRL_REG1
i2c_start();
i2c_write(0x33);
conf1 = i2c_read();
i2c_stop();
printf("\r\nCONF1 = %3u \r\n",conf1); //print it out on the serial link.
i2c_start();
i2c_write(0x32);
i2c_write(0x28 | 0x80);
i2c_start();
i2c_write(0x33);
raw_accel[0] = i2c_read(1);
raw_accel[1] = i2c_read(1);
raw_accel[2] = i2c_read(1);
raw_accel[3] = i2c_read(1);
raw_accel[4] = i2c_read(1);
raw_accel[5] = i2c_read(0);
i2c_stop();
//------------------------
//Temporary! We're going to absolute value the accels.
//------------------------
raw_accel[1] &= 0x0F;
raw_accel[3] &= 0x0F;
raw_accel[5] &= 0x0F;
x_accel = raw_accel[1];
x_accel <<= 8;
x_accel += raw_accel[0];
y_accel = raw_accel[3];
y_accel <<= 8;
y_accel += raw_accel[2];
z_accel = raw_accel[5];
z_accel <<= 8;
z_accel += raw_accel[4];
printf("\r\n X: %Lu Y: %Lu Z: %Lu \r\n",x_accel,y_accel,z_accel);
//Calculate the G's
x_g = (float)x_accel / 1024;
y_g = (float)y_accel / 1024;
z_g = (float)z_accel / 1024;
printf("X: %g G Y: %g G Z: %g G \r\n", x_g, y_g, z_g);
while(1)
{
i2c_start();
i2c_write(0x32);
i2c_write(0x28 | 0x80);
i2c_start();
i2c_write(0x33);
raw_accel[0] = i2c_read(1);
raw_accel[1] = i2c_read(1);
raw_accel[2] = i2c_read(1);
raw_accel[3] = i2c_read(1);
raw_accel[4] = i2c_read(1);
raw_accel[5] = i2c_read(0);
i2c_stop();
x_accel = raw_accel[1];
x_accel <<= 8;
x_accel += raw_accel[0];
y_accel = raw_accel[3];
y_accel <<= 8;
y_accel += raw_accel[2];
z_accel = raw_accel[5];
z_accel <<= 8;
z_accel += raw_accel[4];
// printf("\r\n X: %Lu Y: %Lu Z: %Lu \r\n",x_accel,y_accel,z_accel);
//Calculate the G's
x_g = (float)x_accel / 1024;
y_g = (float)y_accel / 1024;
z_g = (float)z_accel / 1024;
printf("X: %g G Y: %g G Z: %g G \r\n", x_g, y_g, z_g);
delay_ms(100);
}
}