I use the external EEPROM 24LC256 (with resistors 10kohm at SDA and SCL line) with PIC16F877A. My problem is cannot sent/receive the data. Anyone can help me to solve this problem. Below is the program that I use:
- CODE: SELECT_ALL_CODE
#include <pic.h>
__CONFIG ( 0x3F32 );
#define LED RB6
void delay(unsigned long data);
void i2c_init(void);
void i2c_write(unsigned char slave_address, unsigned char addressH, unsigned char addressL, unsigned char uc_data);
unsigned char ee_data;
unsigned char b_i2c_check_error_flag(void);
unsigned char i2c_read(unsigned char slave_address, unsigned char addressH, unsigned char addressL);
unsigned char error_flag = 0;
void main(void)
{
PORTC=0x00;
PORTB=0x00;
TRISB=0x00;
TRISC=0xFF;
i2c_init();
i2c_write(10,0,1,8);
delay(10000);
i2c_read(10,0,1);
delay(1000);
while(1)
{
if(ee_data==8)
{
LED=1;
delay(10000);
LED=0;
delay(10000);
}
else
LED=0;
}
}
void delay(unsigned long data)
{
for( ;data>0;data-=1);
}
void i2c_init(void)
{
TRISC3=1;
TRISC4=1;
SSPCON=0b00101000;
SSPCON2=0x00;
SSPADD=12;
SSPSTAT=0b11000000;
}
unsigned char b_i2c_check_error_flag(void)
{
return error_flag;
}
// I2C READ
unsigned char i2c_read(unsigned char slave_address, unsigned char addressH, unsigned char addressL)
{
error_flag = 0;
SEN = 1;
while (SEN == 1);
SSPBUF = (slave_address << 1) & 0xfe;
while (RW == 1);
if (ACKSTAT == 1)
{
PEN = 1;
while (PEN == 1);
error_flag = 1;
return 0;
}
SSPBUF = addressH;
while (RW == 1);
if (ACKSTAT == 1)
{
PEN = 1;
while (PEN == 1);
error_flag = 1;
return 0;
}
SSPBUF = addressL;
while (RW == 1);
if (ACKSTAT == 1)
{
PEN = 1;
while (PEN == 1);
error_flag = 1;
return 0;
}
RSEN = 1;
while (RSEN == 1);
SSPBUF = (slave_address << 1) | 0x01;
while (RW == 1);
if (ACKSTAT == 1)
{
PEN = 1;
while (PEN == 1);
error_flag = 1;
return 0;
}
RCEN = 1;
unsigned long count = 10000L;
while (BF == 0)
{
if (--count == 0)
{
PEN = 1;
while (PEN == 1);
error_flag = 1;
return 0;
}
}
SSPBUF=ee_data;
ACKDT = 1;
ACKEN = 1;
while (ACKEN == 1);
PEN = 1;
while (PEN == 1);
error_flag = 0;
return ee_data;
}
// I2C WRITE
void i2c_write(unsigned char slave_address, unsigned char addressH, unsigned char addressL, unsigned char uc_data)
{
error_flag = 0;
SEN = 1;
while (SEN == 1);
SSPBUF = (slave_address << 1) & 0xfe;
while (RW == 1);
if (ACKSTAT == 1)
{
PEN = 1;
while (PEN == 1);
error_flag = 1;
return;
}
SSPBUF = addressH;
while (RW == 1);
if (ACKSTAT == 1)
{
PEN = 1;
while (PEN == 1);
error_flag = 1;
return;
}
SSPBUF = addressL;
while (RW == 1);
if (ACKSTAT == 1)
{
PEN = 1;
while (PEN == 1);
error_flag = 1;
return;
}
SSPBUF = uc_data;
while (RW == 1);
if (ACKSTAT == 1)
{
PEN = 1;
while (PEN == 1);
error_flag = 1;
return;
}
PEN = 1;
while (PEN == 1);
error_flag = 0;
}