
#include "pic.h"

/*	Example code for HITECH PICC compiler and PIC16F877

   Compass board uses address 1100000 - 0xc0
   This code shows how to program a PIC16F877 to communicate
   with the compass module via the I2C bus. It uses the hardware
   I2C port on the PIC, this is the MSSP. The PIC is assumed
   to use an 8MHz crystal, otherwise adjust SSPADD in the
   setup routine.
*/


void setup(void);
void read_compass(unsigned char *buffer);



void main(void)
{
unsigned char compass[4], version, bearingB;
unsigned int bearingW;

	setup();

	for(;;) {
		read_compass(compass);
		version = compass[0];
		bearingB = compass[1];
		bearingW =  ((compass[2]<<8) + compass[3]);
//  Do Something with data
	}
}



void read_compass(unsigned char *buffer)
{
	SEN = 1;						// send start bit
	while(SEN);					// and wait for it to clear
	ACKDT = 0;					// acknowledge bit

	SSPIF = 0;
	SSPBUF = 0xC0;				// 11000000 - write command
	while(!SSPIF);				// wait for interrupt
	SSPIF = 0;					// then clear it.

	SSPBUF = 0;					// read from address 0 
	while(!SSPIF);				// 
	SSPIF = 0;					// 

	RSEN = 1;					// send repeated start bit
	while(RSEN);				// and wait for it to clear

	SSPIF = 0;
	SSPBUF = 0xC1;				// 11000001 - read command
	while(!SSPIF);				// wait for interrupt
	SSPIF = 0;					// then clear it.
		
	RCEN = 1;					// start receiving
	while(!STAT_BF);			// wait for data
	buffer[0] = SSPBUF;		// and get it
	ACKEN = 1;					// start acknowledge sequence
	while(ACKEN);				// wait for ack. sequence to end
	
	RCEN = 1;					// start receiving
	while(!STAT_BF);			// wait for data
	buffer[1] = SSPBUF;		// and get it
	ACKEN = 1;					// start acknowledge sequence
	while(ACKEN);				// wait for ack. sequence to end

	RCEN = 1;					// start receiving
	while(!STAT_BF);			// wait for data
	buffer[2] = SSPBUF;		// and get it
	ACKEN = 1;					// start acknowledge sequence
	while(ACKEN);				// wait for ack. sequence to end

	RCEN = 1;					// start receiving
	while(!STAT_BF);			// wait for data
	buffer[3] = SSPBUF;		// and get it
	ACKDT = 1;					// not acknowledge for last byte
	ACKEN = 1;					// start acknowledge sequence
	while(ACKEN);				// wait for ack. sequence to end

	PEN = 1;						// send stop bit
	while(PEN);					//
}


void setup(void)
{
char x;

	__CONFIG(0x3f72);

	TRISC = 0x18;			// RC3-4 are inputs
	SSPSTAT = 0x80;		// slew rate disabled
	SSPCON  = 0x38;		// enable port in 7 bit slave mode
	SSPCON2 = 0x00;		// not a lot
	SSPADD  = 19;			// baud rate in address reg
	x = SSPBUF;				// dummy read clears BF
}

