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

📄 i2c.c

📁 用89C2051实现的软PLC。PLC程序存在24C04,用按健输入程序
💻 C
字号:
#include "reg51.h"
#include "intrins.h"

#define salve_addr 0xa0
#define read   0x01
#define write  0x00;

void I2c_Start();
void I2c_Stop();
void I2c_Wait();
void Ack(bit );
bit Send_Byte(unsigned char);
bit Read_Byte(unsigned char *);

extern unsigned char error;
extern unsigned char data intr[6];
sbit Sda = P1^6;
sbit Scl = P1^7;

bit I2c_Read(unsigned char address,unsigned char count)
{
    unsigned char mode,i;
 
	mode = salve_addr | write;
    I2c_Start();                         error++;
    if (Send_Byte(mode) == 0)
	{                                     error++;
	   if (Send_Byte(address) == 0)
	   {                                    error++;
          I2c_Start();
		  mode = salve_addr | read;
          if (Send_Byte(mode) == 0)
		  {                                  error++;
             for (i = 0;i < count - 1;i++)
 	         {                                 error++;
	            Read_Byte(&intr[i]);
                Ack(0);
             } 
			 Read_Byte(&intr[i]);
			 Ack(1);
   	         if (i == count - 1)
			 {  
			     I2c_Stop();
		         return 0;
			 }
		   }
	   }
	}
	I2c_Stop();
	return 1;                       // error
}

bit I2c_Write(unsigned char address,unsigned char Write_Data)
{
     unsigned char mode;
    
	 mode = salve_addr;
	 mode = mode  | write;
	 I2c_Start();
	 if (Send_Byte(mode) == 0)
	 {  
	     if (Send_Byte(address) == 0)
		     if (Send_Byte(Write_Data) == 0)
  			 {
			      I2c_Stop();
                  return 0;
			 }
	 }
	 I2c_Stop();
	 return 1;
}

void I2c_Start()
{
    Sda = 1;
	Scl = 1;
	I2c_Wait();
	Sda = 0;
	I2c_Wait();
	Scl = 0;
}

void I2c_Stop()
{
    Sda = 0;
	I2c_Wait();
	Scl = 1;
	I2c_Wait();
	Sda = 1;
}

void I2c_Wait()
{
    _nop_();
	_nop_();
}

bit Send_Byte(unsigned char Send_Data)
{
    unsigned char i;
	bit b;
 
	for (i = 0;i < 8;i++)
	{
	   if (Send_Data & 0x80)
	      Sda = 1;
	   else 
	      Sda = 0;
	   Send_Data = Send_Data << 1;
	   Scl = 1;
	   I2c_Wait();
	   Scl = 0;
	   I2c_Wait();
    }
	Sda = 1;
	I2c_Wait();
	Scl = 1;
	I2c_Wait();
    b = Sda;
	Scl = 0;
	I2c_Wait();
	return b;
}

bit Read_Byte(unsigned char *Read_Data)
{
    unsigned char i,temp = 0;

	for(i = 0;i < 8;i++)
	{
	   Scl = 1;
	   I2c_Wait();
	   temp <<= 1;
	   if (Sda == 1)
	      temp = temp | 0x01;
	   Scl = 0;
	   I2c_Wait();
    }
	*Read_Data = temp;
    return 0;
}

void Ack(bit b)
{
    Sda = b;
    Scl = 1;
	I2c_Wait();
	Scl = 0;
	Sda = 1;
}

bit Read_Test(unsigned char address)
{
    bit b;
    I2c_Start();
    b = Send_Byte(0xa0);
	b |= Send_Byte(address);
	I2c_Start();
	b |= Send_Byte(0xa1);
    Read_Byte(&intr[0]);
	Ack(0);
	Read_Byte(&intr[1]);
	Ack(0);
	Read_Byte(&intr[2]);
	Ack(1);
    I2c_Stop();
	return b;
}  

⌨️ 快捷键说明

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