I2c communication with pic 18f452

accelerometerci2cmicrochippic

I am new to pic coding. I am trying to turn motor according to change of accelerometer in x direction. I am using Pic18f452 and adxl345. But I couldnt figure it out how to communicate with adxl345 with using i2c.

Here is my pic code:

int outputs[6];
int x,y,zz;
int px,py,pzz;
int diffx,diffy,diffz;


void motor(int v) {

 PWM1_INIT(2000);
 PWM1_Start();
 if(v>0){
 PORTC.F0=1;          //c0 and c1 is for rotation direction
 PORTC.F1=0;
 }else{
 PORTC.F0=0;
 PORTC.F1=1;
 }

 PWM1_Set_Duty(120);


}

void stopmotor(){
 PWM1_Stop();
}

int i;
 void Read_Data() {


  I2C1_Start();              // issue I2C start signal




  for (i=0;i<6;i++){
  I2C1_Wr(0x32+i);       //read 0x32 to 0x37
  outputs[i] = I2C1_Rd(0);
  I2C1_Stop();
}
}

getDegrees(){
x=(signed) outputs[1]<<8|outputs[0];
y=(signed) outputs[3]<<8|outputs[2];
zz=(signed) outputs[5]<<8|outputs[4];

}

void main() {

 // PORTC.F6 = 0;
//  TRISC.F6 = 0;                 // Configure PORTB as output

PORTB.F0=0;
TRISB.F0=0;
TRISC.F0=0;
TRISC.F1=0;
TRISC.F2=0;



  I2C1_Init(100000);         // initialize I2C communication
  I2C1_Start();              // issue I2C start signal
  I2C1_Wr(0xD2);             // send byte via I2C  (device address + W)
  I2C1_Wr(8);              // for initializing acceloremeter
  I2C1_Stop();               // issue I2C stop signal


  while(1){
  if(x!=0|y!=0|zz!=0){
   px=x;
   py=y;
   pzz=zz;
  }

  Read_Data();
  getDegrees();

if(px!=0|py!=0|pzz!=0){
   diffx=x-px;
   diffy=y-py;
   diffz=zz-pzz;

  }

  if(diffx>0){
      motor(x);


  } else{

  stopmotor();
  }



  delay_ms(500);
  }

}

I know it is not a perfect code but i just want to know weather i am communicating with acceloremeter in a true way or not. While I dont have led screen, I cant see output of data. So I dont have step by step debug options.

How should I modify the code to get output of 0x32-0x37 bits of accelerometer with using i2c?

Best Answer

Have you tried using UART? If you have a USB-TTL adapter, you could connect it to both your PIC and your PC. Alternatively, the PICKit you're probably using also offers UART comms with between your PC and the PIC. I don't know the compiler (or the libraries) you're using, though it looks like Mikro-C, which I've never used. Consult your compiler manuals on how to do the following. You will need to include the necessary header files needed for UART comms, initialize it with a baud rate and other settings, and then you can write a small function that basically accepts a string and prints it to the UART port, character by character, using functions from the UART library you will have imported. On your PC, you can use putty, or the PICKit interface, or even the Arduino serial monitor to view what you get from the PIC. This way, you can get the debug messages you need at every step. Or you could just use an LCD screen, of course ;).