jacquesdejager
Joined: 23 Apr 2011 Posts: 11 Location: South Africa
|
PIC16F87x Hardware I2C Function - 24C256 used for demo code |
Posted: Mon Apr 25, 2011 6:21 am |
|
|
Hi -
Please find below code for hardware i2c on PIC16F87x tested, should work on other PIC micro controllers as well.
I've tested this with a 24C256 EEPROM and all working, still need to implement code in the check library if the I2C device doesn't respond the program will be stuck in the loop.
Hope this is help full to anyone - as I found allot of solutions on this forum and want to contribute as well.
Code: |
#use i2c(MASTER,I2C1,FORCE_HW)
#define I2C_SPEED_DEF 400000
#define I2C_WRITE_ADDRESS_DEF 0xA0
#define I2C_READ_ADDRESS_DEF 0xA1
void i2c_eeprom_init();
int1 i2c_eeprom_ready();
void i2c_eeprom_write(long int address, char data);
char i2c_eeprom_read(long int address);
void i2c_eeprom_init() {
set_tris_c(0b00011011);
i2c_speed(I2C_SPEED_DEF);
}//init_i2c_eeprom
int1 i2c_eeprom_ready() {
int1 ack;
i2c_start();
ack = i2c_write(I2C_WRITE_ADDRESS_DEF);
i2c_stop();
return !ack;
}//
void i2c_eeprom_write(long int address, char data) {
while(!i2c_eeprom_ready());
i2c_start();
i2c_write(I2C_WRITE_ADDRESS_DEF);
i2c_write((char)(address >> 8));
i2c_write((char)address);
i2c_write(data);
i2c_stop();
}//write_i2c_eeprom
char i2c_eeprom_read(long int address) {
char data;
while(!i2c_eeprom_ready());
i2c_start();
i2c_write(I2C_WRITE_ADDRESS_DEF);
i2c_write((char)(address >> 8));
i2c_write((char)address);
i2c_start();
i2c_write(I2C_READ_ADDRESS_DEF);
data = i2c_read(0);
i2c_stop();
return(data);
}//read_i2c_eeprom
|
|
|