#include "iic.h"
#include "delay.h"

//初始化IIC
  void IIC_Init(void)
{
	GPIO_InitTypeDef GPIO_InitTypeStruct;
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB,ENABLE);
  

  GPIO_InitTypeStruct.GPIO_Pin = GPIO_Pin_8|GPIO_Pin_9;
	GPIO_InitTypeStruct.GPIO_Mode = GPIO_Mode_OUT;
	GPIO_InitTypeStruct.GPIO_OType = GPIO_OType_PP;
	GPIO_InitTypeStruct.GPIO_PuPd = GPIO_PuPd_UP;
	GPIO_InitTypeStruct.GPIO_Speed = GPIO_Speed_100MHz;
  GPIO_Init(GPIOB,&GPIO_InitTypeStruct);
	
	IIC_SCL = 1;
	IIC_SDA = 1;
}


//产生起始信号
  void IIC_Start(void)
	{ 
		SDA_OUT();
		IIC_SDA = 1; IIC_SCL = 1;
		delay_us(4);
		IIC_SDA = 0; 
		delay_us(4);
		IIC_SCL = 0;
	}
	
//产生停止信号
	void IIC_Stop(void)
	{
	  SDA_OUT();
		IIC_SCL = 0;
		IIC_SDA = 0;
		delay_us(4);
		IIC_SCL = 1;IIC_SDA = 1;
		delay_us(4);
	}
	
	
//产生应答信号
	 void IIC_Ack(void)
	 {
		 IIC_SCL = 0;
		 SDA_OUT();
		 IIC_SDA = 0;
		 delay_us(2);
		 IIC_SCL = 1;
		 delay_us(2);
		 IIC_SCL = 0;
	 }
	 
//不产生应答信号
	 void IIC_No_Ack(void)
	 {
		 IIC_SCL = 0;
		 SDA_OUT();
		 IIC_SDA = 1;
		 delay_us(2);
		 IIC_SCL = 1;
		 delay_us(2);
		 IIC_SCL = 0;
	 }
	 
//等待应答信号到来
//返回1：失败
//返回0：成功
	 u8 IIC_Wait_Ack(void)
	 {
		 u8 ucErrTime = 0;
		 SDA_IN();
		 IIC_SDA = 1;
		 delay_us(1);
		 IIC_SCL = 1;
		 delay_us(1);
		 
		 while(READ_SDA)
		 {
			 ucErrTime++;
			 if(ucErrTime>250)
			 {
				 IIC_Stop();
			   return 1;
			 }
		 }
	   IIC_SCL = 0;
		 return 0;
	 }
	 
	 
//IIC发送一个字节

	 void IIC_Send_Byte(u8 dat)
	 {
		 u8 i;
		 SDA_OUT();
		 IIC_SCL = 0;
		 for(i=0;i<8;i++)
		 {
			 IIC_SDA = (dat&0x80)>>7;
			 dat <<= 1;
			 delay_us(2);
			 IIC_SCL = 1;
			 delay_us(2);
			 IIC_SCL = 0;
			 delay_us(2);
		 }
	 }
	 
//读取iic字节
//ack=0,发送NO_ACK
//ack=1,发送ACK
	 u8 IIC_Read_Byte(u8 ack)
	 {
		 u8 i,receive = 0;
		 SDA_IN();
		 for(i=0; i<8; i++)
		 {
			 IIC_SCL = 0;
			 delay_us(2);
			 IIC_SCL = 1;
			 receive<<=1;
			 if(READ_SDA)
				 receive++;
			 delay_us(1);
		 }
	   if(!ack)
			 IIC_No_Ack();
		 else
			 IIC_Ack();
		 return receive;
	 }
	 
	 
	 
	

	 
	 