⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 i2cbus.c

📁 正交信号源的单片机和cpld源码
💻 C
字号:

#include "..\inc\I2CBus.h"
#include "intrins.h"

static void  I2CStart(void);
static void  I2CStop(void);
//static void  I2CSendAck(void);
//static void  I2CSendNotAck(void);
static bit   I2CSendByte(uchar);
//static uchar I2CRevByte();

bit EAFlag;         //   中断标志位

bit I2CSendBuf(uchar *pBuf, uchar Len)
{
	I2CStart();

	while(Len--)
	{
		if (I2CSendByte(*pBuf++) == 0)
		{
		    I2CStop();
			return 0;
		}
	}

	I2CStop();
	return 1;
}

void I2CStart()
{
	EAFlag = EA;
	EA     = 0;

	SDA = 1;
	DELAY_2us();
	SCL = 1;
	DELAY_4us();
	SDA = 0;
	DELAY_4us();
	SCL = 0;
}

void I2CStop()
{
	SDA = 0;

	DELAY_2us();
	SCL = 1;
    DELAY_4us();
	SDA = 1;
	DELAY_4us();
	SCL = 0;

	EA = EAFlag;
}

/*------------------------------------------------------------------------------*-
Send a byte, the following will wait for ACK from the slave device
-*------------------------------------------------------------------------------*/
bit I2CSendByte(uchar Data)
{
	uchar i;
	uchar timeout = 0xff;

	for (i = 0; i < 8; i++)
	{
		if ((Data << i) & 0x80)
		{
			SDA = 1;
		}
		else
		{
			SDA = 0;
		}

		DELAY_2us();
		SCL = 1;
		DELAY_4us();
		SCL = 0;
	}

	SDA = 1;
    DELAY_2us();
	SCL = 1;
	DELAY_4us();

    while (SDA);                    // 等待应答
	{
		if(--timeout == 0)
		{
			return 0;               // 0 表示发送失败
        }
	}

	SCL = 0;

	return 1;                        // 1 表示发送成功
}

#if (SEND_ACK_ENB)
uchar I2CRevByte()
{
    uchar i=8;
	uchar ddata;
	SDA=1;

  	while (i--)
  	{
  		ddata<<=1;
  		SCL=0;
		DELAY_2us();
  		SCL=1;
		DELAY_4us();
  		ddata|=SDA;
  	}

  	SCL=0;
  	return ddata;
}
#endif

/*--------------------------------------------------------------------------------
 调用方式:void I2CSendAck(void) ﹫2001/07/0 4
 函数说明:主器件为接收方,从器件为发送方时,应答信号。
-*---------------------------------------------------------------------------------*/
#if (SEND_ACK_ENB)
void I2CSendAck(void)
{
    SDA=0; 
    DELAY_2us();
	SCL=1; 
	DELAY_4us();
	SCL=0;
}
#endif
/*--------------------------------------------------------------------------------
 调用方式:void SendAck(void) ﹫2001/07/0 4
 函数说明:主器件为接收方,从器件为发送方时,非应答信号。
--------------------------------------------------------------------------------*/

/*
void I2CSendNotAck(void)
{
 	SDA=1;
 	DELAY_4us(); 
 	SCL=1;
 	DELAY_8us(); 
 	SCL=0;
}
*/

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -