#include"intrins.h"
#include"iic.h"
sbit SCL = P2^0;
sbit SDA = P2^1;
//#define SCL P20
//#define SDA P21
void IIC_Start()
{
SCL = 1;
SDA = 1;
delay2us();
SDA = 0;
delay2us();
SCL = 0;
}
void IIC_Stop()
{
SDA = 0;
SCL = 1;
delay2us();
SDA = 1;
delay2us();
}
void Write_IIC(unsigned char dat)
{
unsigned char i;
EA = 0;
for(i=0; i<8; i++)
{
SCL = 0;
delay2us();
if(dat & 0x80)
{ SDA = 1; }
else
{ SDA = 0; }
delay2us();
SCL = 1;
delay2us();
dat <<= 1;
delay2us();
}
EA = 1;
SCL = 1;
}
unsigned char Read_Iic()
{
unsigned char i,dat;
EA = 0;
for(i=0; i<8; i++)
{
SCL = 1;
delay2us();
dat <<= 1;
if(SDA)
dat |= 0x01;
//delay2us();
SCL = 0;
delay2us();
}
EA = 1;
return dat;
}
void IIC_SendAck(unsigned char ack)
{
SCL = 0;
SDA = ack; delay2us();
SCL = 1; delay2us();
SCL = 0;
SDA = 1;
delay2us();
}
unsigned char IICRead_Byte(unsigned char add)
{
unsigned char dat;
IIC_Start();
Write_IIC(0xA0);
IIC_Ack();
Write_IIC(add);
IIC_Ack();
IIC_Start();
Write_IIC(0xA1);
IIC_Ack();
dat = Read_Iic();
IIC_SendAck(0);
IIC_Stop();
return dat;
}
void IICWrite_Byte(unsigned char add, unsigned char dat)
{
IIC_Start();
Write_IIC(0xA0);
IIC_Ack();
Write_IIC(add);
IIC_Ack();
Write_IIC(dat);
IIC_Ack();
IIC_Stop();
delay2us();delay2us();delay2us();delay2us();delay2us();delay2us();delay2us();delay2us();
}
unsigned char IIC_Ack()
{
unsigned char count;
SCL = 1;delay2us();
count = SDA;
SCL = 0;delay2us();
return count;
}
void delay2us()
{
unsigned char i = 5;
do
{
_nop_();_nop_();_nop_();_nop_();_nop_();
_nop_();_nop_();_nop_();_nop_();_nop_();
_nop_();_nop_();_nop_();_nop_();_nop_();
}
while(i--);
}