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

📄 at24cxx.c

📁 实现80c51系列单片机IIC芯片的读写
💻 C
字号:
#include<reg51.h>
#define uchar unsigned char
#define uint unsigned int


sbit SCL=P1^0;  //接存储器串口
sbit SDA=P1^1;  //接存储器数据口


uchar WData[8]={0x03,0x23,0x12,0xab,0xaa,0xbb,0xff,0xee};
uchar RData[8]={0};

void DelayMs(unsigned int number)	
{
  unsigned char temp;
  for(;number!=0;number--)
   {
	 for(temp=80;temp!=0;temp--)
	  {
	  }
   }
}

void Start()
{ SDA=1;
  SCL=1;
  DelayMs(1);
  SDA=0;
  DelayMs(1);
  SCL=0;
}


void Stop()
{ SDA=0;
  SCL=1;
  DelayMs(1);
  SDA=1;
  DelayMs(1);
  SCL=0;
}

void NoAck()
{ SDA=1;
  SCL=1;
  DelayMs(1);
  SCL=0;
  DelayMs(1);
}

void FreeBus()
{ SCL=0;
  SDA=1;
  SCL=1;
}

uchar TestAck()
{ uchar i=0;
  SCL=1;
  i=SDA;
  return i;
}

void BeSureAck()
{ FreeBus();
  TestAck();  
//while(TestAck())
   //{};
  DelayMs(1);
}

void WriteByte(uchar Mesg)
{ uchar i;
 for(i=0;i<8;i++)
   { SCL=0;
     SDA=(bit)(Mesg&0x80);
	 SCL=1;
	 DelayMs(1);
	 SCL=0;
	 Mesg<<=1;
   }
}

void WriteNByte(uchar n,WAddress,RomAddress)
{ uchar temp=0;
  Start();
  WriteByte(WAddress);
  BeSureAck();
  WriteByte(RomAddress);
  BeSureAck();
  for(temp=0;temp<n;temp++)
   { WriteByte(WData[temp]);
     BeSureAck();
   }
  Stop();
}


uchar ReadByte()
{ uchar Mesg=0;
  uchar i=0;
  for(i=0;i<8;i++)
   { SCL=1;
     DelayMs(1);
	 Mesg<<=1;
     Mesg=(uchar)SDA;
	 SCL=0;
	 
   }
  return Mesg;
}


void ReadNByte(uchar n,RAddress,RomAddress)
{ uchar temp=0;
  Start();
  WriteByte(RAddress);
  BeSureAck();
  WriteByte(RomAddress);
  BeSureAck();
  Start();
  WriteByte(RAddress);
  BeSureAck();
  for(temp=0;temp<n;temp++)
   { RData[temp]=ReadByte();
     BeSureAck();
   }
   NoAck();
   Stop();
}





⌨️ 快捷键说明

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