mikroC PRO PIC comes with an example of I2C eeprom. Use it. It works for me.
- - - Updated - - -
Edit:
Code:
I2C1_Init(100000); // initialize I2C communication
I2C1_Start(); // issue I2C start signal
I2C1_Wr(0xA2); // send byte via I2C (device address + W)
I2C1_Wr(2); // send byte (address of EEPROM location)
I2C1_Wr(0xAA); // send data (data to be written)
I2C1_Stop(); // issue I2C stop signal
Delay_100ms();
I2C1_Start(); // issue I2C start signal
I2C1_Wr(0xA2); // send byte via I2C (device address + W)
I2C1_Wr(2); // send byte (data address)
I2C1_Repeated_Start(); // issue I2C signal repeated start
I2C1_Wr(0xA3); // send byte (device address + R)
LATB = I2C1_Rd(0u); // Read the data (NO acknowledge)
I2C1_Stop(); // issue I2C stop signal
I2C1_Init(100000);
//I2C1 communication is initialized at 100 kbps baudrate
//I2C1 communication is started, only master controls the I2C clock
//The address byte for AT24LC64 is formed like this
bits 7 to bits 4 will be 1010. This is the 4bit control code for read or write.
bits 3 to 1 for the actual address set on the eeprom chip. Here it is 001
bit 0 is Read/Write bit.
Here we are writing to eeprom so bit 0 is 0 and so the address byte becomes
1010 001 0 = 10100010 = 0xA2
Next he is sending address of eeprom location (2).
So the data that will be sent next will be written at eeprom address 0x02
Now data 0xAA is written at address 0x02 of eeprom
I2C communication is stopped.
Now reading data from eeprom and displaying the read byte on PORTB.
These three lines are already explained
Code:
I2C1_Start(); // issue I2C start signal
I2C1_Wr(0xA2); // send byte via I2C (device address + W)
I2C1_Wr(2); // send byte (data address)
Now a repeated start signal is issued
Now read address has to be sent so in the address byte the bit 0 will be 1
so the address byte will be
1010 001 1 = 10100011 = 0xA3
Read address is sent.
eeprom sends data at address 0x02.
master reads the data and does a not ack.
I2C communication is stopped