#include "iic.h"
#include "yc11xx.h"
//总线引脚定义
#define SDA 6
#define SCL 25
#define IIC_HIGH (0x3f)
#define IIC_LOW  (0x3e)
#define IIC_RCV 0x40
void Delay()		//@11.0592MHz
{
	while(0);
	
}

//总线启动条件
void IIC_Start(void)
{

	HWRITE(0x8080+SCL,IIC_HIGH);
	HWRITE(0x8080+SDA,IIC_HIGH);
	Delay();
	HWRITE(0x8080+SDA,IIC_LOW);
	Delay();
	HWRITE(0x8080+SCL,IIC_LOW);	
}

//总线停止条件
void IIC_Stop(void)
{
	HWRITE(0x8080+SCL,IIC_LOW);
	HWRITE(0x8080+SDA,IIC_LOW);
	Delay();
	HWRITE(0x8080+SCL,IIC_HIGH);
	Delay();
	HWRITE(0x8080+SDA,IIC_HIGH);
	
}

//发送应答
void IIC_SendAck(unsigned char ackbit)
{
	HWRITE(0x8080+SCL,IIC_LOW);
	HWRITE(0x8080+SDA,(ackbit));
	Delay();
	HWRITE(0x8080+SCL,IIC_HIGH);
	Delay();
	HWRITE(0x8080+SCL,IIC_LOW); 
	//HWRITE(0x8080+SDA,IIC_HIGH);
	//Delay();
}

//等待应答
unsigned char IIC_WaitAck(void)
{
	HWRITE(0x8080+SDA,IIC_RCV|0x40);
	HWRITE(0x8080+SCL,IIC_LOW);
	Delay();
	HWRITE(0x8080+SCL,IIC_HIGH);
	int cnt=0;
	while(HREAD(0x831c)&0x10){
		cnt++;
		Delay();
		if(cnt>256)return 0;
	};
	HWRITE(0x8080+SCL,IIC_LOW);
	Delay();
	return 1;
}

//通过I2C总线发送数据
void IIC_SendByte(unsigned char byt)
{
	unsigned char i;
	for (i = 0; i < 8; i++) {
		HWRITE(0x8080+SCL,IIC_LOW);
		Delay();
		if (byt & 0x80)
			HWRITE(0x8080+SDA,IIC_HIGH);
		else
			HWRITE(0x8080+SDA,IIC_LOW);
		Delay();
		HWRITE(0x8080+SCL,IIC_HIGH);
		byt <<= 1;
		Delay();
	}
	HWRITE(0x8080+SCL,IIC_LOW);  
	//HWRITE(0x8080+SDA,IIC_HIGH);
}

//从I2C总线上接收数据
unsigned char IIC_RecByte(void)
{
	unsigned char i, da;
	da=0;
	HWRITE(0x8080+SDA,IIC_RCV);
	for (i = 0; i < 8; i++) {   
		HWRITE(0x8080+SCL,IIC_LOW);
		Delay();
		HWRITE(0x8080+SCL,IIC_HIGH);
		da <<= 1;
		if (HREAD(CORE_GPIO_IN)&(1<<SDA))
			da |= 1;
		Delay();
	}
	//HWRITE(0x8080+SDA,IIC_HIGH);
	return da;    
}
void IIC_ReceiveData(unsigned char *Src, unsigned short Srclen, unsigned char *Dest, unsigned short Destlen){
	IIC_Start();
	for(int i=0;i<2;i++){
		IIC_SendByte(Src[i]);
		IIC_WaitAck();
		//if(i==1)IIC_Start();
	}
	IIC_Start();
	for(int i=2;i<Srclen;i++){
		IIC_SendByte(Src[i]);
		IIC_WaitAck();
	}
	for(int i=0;i<Destlen-1;i++){
		Dest[i]=IIC_RecByte();
		IIC_SendAck(0x3e);
	}
	Dest[Destlen-1]=IIC_RecByte();
	IIC_SendAck(0x3f);
	IIC_Stop();
}
void IIC_SendData(unsigned char *Src, unsigned short len){
	IIC_Start();
	for(int i=0;i<len;i++){
		IIC_SendByte(Src[i]);
		IIC_WaitAck();	
	}	
	IIC_Stop();
}