koolguy
Active Member
Hi,
I am using atmlu020 EEPROM with AD0 - AD2 to GND
and testing whether the send data is matched from reading data at same addr by switching LED On Pin...
so, here is the code don't know why the if statement looping cont and led is blinking??
I am using atmlu020 EEPROM with AD0 - AD2 to GND
and testing whether the send data is matched from reading data at same addr by switching LED On Pin...
so, here is the code don't know why the if statement looping cont and led is blinking??
Code:
#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);
unsigned char i2c_Read(unsigned char ack);
void main(void){
TRISC3=1; //direction to input have be changed
TRISC4=1;
unsigned char ch,c;
TRISC5=0;
TRISD2=0;
__delay_ms(200);
RD2=1;
c=0xff;
while(1){
I2C_init();
__delay_ms(50);
I2C_start();
I2C_write(0b10100000);//command 1010 and 000 and 0 for write
I2C_write(0X10);// addr at location
I2C_write(0XFF);//data
I2cSTOP();
I2C_init();
__delay_ms(50);
I2C_start();
I2C_write(0b10100001);//command 1010 and 000 and 0 for read
I2C_write(0X10);// addr
ch= i2c_Read(0); //read data
I2cSTOP();
if(ch&&0X0F){ // comparing data with ch
RD2=0;
__delay_ms(400);
RD2=1;
__delay_ms(800);
}
else{
RD2=0;
}
ch=0;
}
}
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;
}
unsigned char i2c_Read(unsigned char ack)
{
// Read data from slave
// ack should be 1 if there is going to be more data read
// ack should be 0 if this is the last byte of data read
unsigned char i2cReadData;
i2c_Wait();
RCEN=1;
i2c_Wait();
i2cReadData = SSPBUF;
i2c_Wait();
if ( ack ) ACKDT=0; // Ack
else ACKDT=1; // NAck
ACKEN=1; // send acknowledge sequence
return( i2cReadData );
}