/**************************************************************************
Dbt_I2C_test_c
Sends single character, and then string, periodically on I2C. 
Set up as Master.
Files c018i.o and p18f242.lib are included by the Linker Script. 
TJW 12.11.05											Tested 4.12.05
**************************************************************************
Clock is 4MHz. Configuration Word: WDT off, power-up timer on, brown-out 
detect off, code protect off, crystal oscillator (HS). All others default*/

	#include <p18F242.h>
	#include <i2c.h>			//header file for I2C
	#include <delays.h>			//header file for delays
	#define slave_addr1 0xA4 	//Adress of Derbot Hand Controller I2C node.

//Function Prototypes. Library function prototypes are found in Header file
	void diagnostic (void);

//constants & variables
	unsigned char message[] = " Derbot";
	unsigned char *i = &message[0];  //pointer to message[]	
	char loop_cntr = 0;
/***********************************************************************
This is main function. 
/**********************************************************************/
	void main (void)
{
//Initialise Ports
	TRISA = 0b00001011;			//ADC channels set as inputs	
	TRISB = 0b11001000;
	TRISC = 0b10011000; 		//I2C bits are both set as ip
//Switch all outputs off
	PORTA = PORTB = PORTC = 0;
//call diagnostic function (flash leds)
	diagnostic();	
//Initialise I2C
	OpenI2C (MASTER, SLEW_OFF);
	SSPADD = 0x07; 				//set up 125kHz baud rate
loop:
//Send single character
	i = &message[0];
 	StartI2C();			   		//send start condition 
	WriteI2C (slave_addr1); 	//send address word, function waits until 
									//write is complete
	loop_cntr = loop_cntr|0x30; //convert counter to ASCII
	WriteI2C (loop_cntr);
	loop_cntr = loop_cntr&0x0F; //retrieve counter from ASCII
 	StopI2C();					//send stop condition
	Delay10KTCYx (100);
//Send a string
 	StartI2C();			   		//send start condition
	WriteI2C (slave_addr1); 	//send address word, function waits until 
									//write is complete
	while (*i)					//Test for null character
	{
	WriteI2C (*i);
	i++;
	Delay1KTCYx (5);			//delay needed for hand controller
	}
	StopI2C();					//send stop condition
	Delay10KTCYx (100);
	loop_cntr++;
	if 	(loop_cntr == 10) loop_cntr = 0;
	goto loop;	
}					//end of main

//Diagnostic: switches leds on for 1s (Tcy = 1us)
void diagnostic (void)
{	Delay10KTCYx (50);
	PORTCbits.RC6 = 1;
	PORTCbits.RC5 = 1;
	Delay10KTCYx (100);
	PORTCbits.RC6 = 0;
	PORTCbits.RC5 = 0;
	Delay10KTCYx (100);
}
