#include <htc.h>
__CONFIG(LVP_OFF & BOREN_OFF & PWRTE_ON & WDTE_OFF & FOSC_HS);
#define _XTAL_FREQ 20000000
#define SDATA RC4
#define SCLK RC3
void I2C_init(),I2C_start(void),I2C_write(char x), I2cSTOP(void);
void i2c_Wait(void);
char data[13]={ 0b00010000,0b01111101,0b00100011,0b00101000,0b01001101,0b10001000,
0b10000000, 0b00111101,0X00,0b00001000};
unsigned char I2CData[] = {0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x09, 0x00}; // Buffer where we will read/write our data
void main(void){
ANSELH = 0;
TRISC3=1; //direction to input have be changed
TRISC4=1;
unsigned char ch=0;
unsigned char i;
TRISC0=0;
TRISB=0X00;
TRISD=0X00;
TRISC1=0;
TRISC2=0;
RC0=0;
RC1=0;
RC2=0;
__delay_ms(500);
I2C_init();
__delay_ms(50);
I2C_start();
I2C_write(0xd0);//esc default addr
I2C_write(0x00);//esc default addr
/* Loop to write 8 bytes */
for (i = 0; i < 8; i++) {
/* send I2C data one by one */
I2C_write(I2CData[i]);
}
I2cSTOP();
while(1){
I2C_start();
I2C_write(0xd0);//esc default addr
I2C_write(0x00);//esc default addr
I2C_start();
I2C_write(0xd1);//esc default addr
I2C_write(0xD1);
for (i = 8; i > 0; i--) {
I2CData[i]= I2CRead();
/* ACK if its not the last byte to read */
/* if its the last byte then send a NAK */
if (i - 1)
I2CAck();
else
I2CNak();
}
I2CStop();
}
//ch = I2C_Read();
RD0=0;
RD1=0;
RD2=0;
RD3=1;
PORTB=data[ch];
__delay_ms(500);
PORTB=0B00000000;
}
void I2C_init(void)
{
SSPCON = 0x38; // set I2C master mode
SSPCON2 = 0x00;
SSPADD = 0x0C; //400KHZ 20MHz xtal
SSPSTAT|=0X80;
PSPIF=0; // clear SSPIF interrupt flag
BCLIF=0; // clear bus collision flag
}
void I2C_start(void)
{
i2c_Wait();
SEN=1;
}
void I2C_write(char x){
i2c_Wait();
SSPBUF=x;
}
void i2c_Wait(void){
while((SSPCON2 & 0X1F || (SSPSTAT & 0X04)));
}
void I2cSTOP(void)
{
i2c_Wait();
PEN=1;
}