#include <reg51.h>

#define Dlzka	6

sbit	SDA = P3^2;
sbit	SCL	=	P3^3;

extern void Delay(unsigned char);

void I2C_Start(void)
{
 SCL=SDA=1;			//AGSI drivers vyzaduje !!!, Zacalo davat dobre vysledky s AGSI drivers
 Delay(Dlzka);	//AGSI drivers vyzaduje !!!, Zacalo davat dobre vysledky s AGSI drivers
 SDA=0;
 Delay(Dlzka);
 SCL=0;
 Delay(Dlzka);
}

void I2C_Bit(unsigned char Data)
{
 SDA=Data;
 Delay(Dlzka);
 SCL=1;
 Delay(Dlzka);
 SCL=0;
 Delay(Dlzka);
}

unsigned char I2C_ReadBit(void)
{
 register unsigned char Result;
 #ifndef SIMUL
  SDA=1;				//Zacalo davat dobre vysledky s 80C552 na BAST552....
 #endif
 Delay(Dlzka);
 SCL=1;
 Delay(Dlzka);
 Result=SDA;
 Delay(Dlzka);
 SCL=0;
 Delay(Dlzka);
 return(Result);
}

void I2C_Stop(void)
{
 SDA=0;
 Delay(Dlzka);
 SCL=1;
 Delay(Dlzka);
 SDA=1;
 Delay(Dlzka);
}

unsigned char I2C_Read(unsigned char doACK)
{
 register unsigned char i, Result=0;
 for(i=0x00; i<0x08; i++)
  {
   Result<<=1;
   Result|=(I2C_ReadBit()&0x01);
  }
 if(doACK==0) I2C_Bit(1);  /* No ACK */ else I2C_Bit(0);  /* Do the ACK */
 return(Result);
}

unsigned char I2C_SendByte(unsigned char Data)
{
 register unsigned char i;
 for(i=0x00; i<0x08; i++)
  {
   if(Data&0x80) I2C_Bit(1); else I2C_Bit(0);
   Data<<=1;
  }
 return(I2C_ReadBit());	
}

unsigned char I2C_SendAddr(unsigned char Addr)
{
 I2C_Start();
 return(I2C_SendByte(Addr));
}

#ifdef BLOCK

unsigned char i2c_writeblock(unsigned char Addr, unsigned char *barr,int length)
{
  register int i;
  if(I2C_SendAddr(Addr&0xFE)!=0) return(1);
  for(i=0x00;i<length;i++) if(I2C_SendByte(barr[i])!=0) return(1);
  I2C_Stop();
  return(0);
}

unsigned char i2c_readblock(unsigned char Addr, unsigned char *barr,int length)
{
  register int i;
  if(I2C_SendAddr(Addr|0x01)!=0) return(1);
  // Reduce the length by one.  The last byte must not be ACKed.
  length--;
  // Read every byte but the last
  for(i=0x00; i<length;i++) barr[i]=I2C_Read(1);
  // Don't ack the last byte
  barr[i]=I2C_Read(0);
  I2C_Stop();
  return(0);
}

unsigned char i2c_writereadblock(unsigned char Addr, unsigned char *barr1,int length1, unsigned char *barr2,int length2)
{
  register int i;
  if(I2C_SendAddr(Addr&0xFE)!=0) return (1);
  for(i=0x00; i<length1;i++) I2C_SendByte(barr1[i]);
  SDA=1;
  Delay(Dlzka);
  SCL=1;
  Delay(Dlzka);
  if(I2C_SendAddr(Addr|0x01)!=0) return(1);
  // Reduce the length by one.  The last byte must not be ACKed.
  length2--;
  // Read every byte but the last
  for(i=0x00;i<length2;i++) barr2[i]=I2C_Read(1);
  // Don't ack the last byte
  barr2[i]=I2C_Read(0);
  I2C_Stop();
  return(0);
}

#endif