Will the following code work, if I implement it on 89s52?
/* Hardware-Specific Support Functions That MUST Be Customized */
#define I2CSPEED 100
void I2CDELAY(int delay) {volatile int v; int i; for(i=0;i<delay;i++) v;}
unsigned READSCL(void) {return(1);} /* Return current level of SCL line, 0 or 1 */
unsigned READSDA(void) {return(1);} /* Return current level of SDA line, 0 or 1 */
void CLRSCL(void) {}
void CLRSDA(void) {}
void ARBITRATION_LOST(void) {}
/* Global Data */
unsigned start = 0;
void i2c_start_cond(void)
{
/* if start == 1, do a restart cond */
if (start)
{
/* set SDA to 1 */
READSDA();
I2CDELAY(I2CSPEED/2);
/* Clock stretching */
while (READSCL() == 0); /* You should add timeout to this loop */
}
if (READSDA() == 0)
{
ARBITRATION_LOST();
}
/* SCL is high, set SDA from 1 to 0 */
CLRSDA();
I2CDELAY(I2CSPEED/2);
CLRSCL();
start = 1;
}
void i2c_stop_cond(void)
{
/* set SDA to 0 */
CLRSDA();
I2CDELAY(I2CSPEED/2);
/* Clock stretching */
while (READSCL() == 0); /* You should add timeout to this loop */
/* SCL is high, set SDA from 0 to 1 */
if (READSDA() == 0)
{
ARBITRATION_LOST();
}
I2CDELAY(I2CSPEED/2);
start = 0;
}
/* Write a bit to I2C bus */
void i2c_write_bit(unsigned bit)
{
if (bit)
{
READSDA();
}
else
{
CLRSDA();
}
I2CDELAY(I2CSPEED/2);
/* Clock stretching */
while (READSCL() == 0); /* You should add timeout to this loop */
/* SCL is high, now data is valid */
/* If SDA is high, check that nobody else is driving SDA */
if (bit)
{
if (READSDA() == 0)
{
ARBITRATION_LOST();
}
}
I2CDELAY(I2CSPEED/2);
CLRSCL();
}
/* Read a bit from I2C bus */
unsigned i2c_read_bit(void)
{
unsigned bit;
/* Let the slave drive data */
READSDA();
I2CDELAY(I2CSPEED/2);
/* Clock stretching */
while (READSCL() == 0); /* You should add timeout to this loop */
/* SCL is high, now data is valid */
bit = READSDA();
I2CDELAY(I2CSPEED/2);
CLRSCL();
return bit;
}
/* Write a byte to I2C bus. Return 0 if ack by the slave */
unsigned i2c_write_byte(int send_start, int send_stop, unsigned char byte)
{
unsigned bit;
unsigned nack;
if (send_start)
{
i2c_start_cond();
}
for (bit = 0; bit < 8; bit++)
{
i2c_write_bit(byte & 0x80);
byte <<= 1;
}
nack = i2c_read_bit();
if (send_stop)
{
i2c_stop_cond();
}
return nack;
}
/* Read a byte from I2C bus */
unsigned char i2c_read_byte(int nak, int send_stop)
{
unsigned char byte = 0;
unsigned bit;
for (bit = 0; bit < 8; bit++)
{
byte <<= 1;
byte |= i2c_read_bit();
}
i2c_write_bit(nak);
if (send_stop)
{
i2c_stop_cond();
}
return byte;
}