// Header:
// File Name:
// Author:
// Date:
#include "MDRFxx_SFR.h"
#include "main.h"
#include "i2c.h"

// I2C 24C02
sbit SCL = P0^7;	//24c02 clock
sbit SDA = P3^0;	//24C02 data

#define SLAVEADDR  0xA0

xdata unsigned char i2c_Cnt;
bit i2c_Busy;
bit i2c_Save;

void delay_us (void)
{
	char a = 2;
	while(a--);
}

void delay(unsigned int cnt)
{
	unsigned int i;
	for (i=0; i<cnt; i++);
}

void i2c_start(void)
{
	SDA = 1;
	delay_us();
	SCL = 1;
	delay_us();
	SDA = 0;
	delay_us();
	SCL = 0;
}

void i2c_stop()
{
	SCL = 0;
	delay_us();
	SDA = 0;
	delay_us();
	SCL = 1;
	delay_us();
	SDA = 1;
	delay_us();
}

void i2c_ACK(bit ck)
{
	if (ck)
	SDA = 0;
	else
	SDA = 1;
	delay_us();
	SCL = 1;
	delay_us();
	SCL = 0;
	SDA = 1;
	delay_us();
}

bit i2c_waitACK()
{
	SDA = 1;
	delay_us();
	SCL = 1;
	delay_us();
	if (SDA)
	{
		SCL = 0;
		i2c_stop();
		return 0;
	}
	else
	{
		SCL = 0;
		return 1;
	}
}

void i2c_sendbyte(unsigned char bt)
{
	unsigned char i;
	for(i=0; i<8; i++)
	{  
		if (bt & 0x80) SDA = 1;
		else           SDA = 0;
		delay_us();
		SCL = 1;
		bt <<= 1;
		delay_us();
		SCL = 0;
	}
}

unsigned char i2c_recbyte()
{
	unsigned char dee, i;
	for (i=0; i<8; i++)
	{
		SCL = 1;
		delay_us();
		dee <<= 1;
		if (SDA) dee = dee | 0x01;
		SCL = 0;
		delay_us();
	}
	return dee;
}

void i2c_writebyte(unsigned char add,unsigned char dat)
{
	i2c_start();
	i2c_sendbyte(SLAVEADDR);  //device address+W+ACK
	i2c_waitACK();
	i2c_sendbyte(add);   //Word address+ACK
	i2c_waitACK();
	i2c_sendbyte(dat);   //1Byte data+ACK
	i2c_waitACK();
	i2c_stop();
	delay(200);
//	SCL = 0;
}

unsigned char i2c_readbyte(unsigned char add)
{
	unsigned char hep;
	i2c_start();
	i2c_sendbyte(SLAVEADDR);    //device address+W+ACK
	i2c_waitACK();
	i2c_sendbyte(add);          //Word address+AC
	i2c_waitACK();
	i2c_start();
	i2c_sendbyte(SLAVEADDR+1);  //device address+R+ACK
	i2c_waitACK();
	hep = i2c_recbyte();        //start read data
	i2c_ACK(0);                 // No ACK
	i2c_stop();   
	return hep;
}