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

📄 i2c.h

📁 非常好的单片机汇编语言
💻 H
字号:
#ifndef __I2C_H__
#define __I2C_H__
/***********************************************************************
 24C08.C
 ************************************************************************/
#include <reg52.h>
#include <intrins.h>

#define uchar unsigned char
#define uint  unsigned int
sbit scl=P3^4;
sbit sda=P3^3;

void I2C_Delay(uint j)   //延时程序
{
	while(j--)
	{
 		_nop_();
		
			
	}
}


void Start()       //启动程序
{
	 sda=1;
	 scl=1;
	 _nop_();
	 _nop_();
	 _nop_();
	 _nop_();
	 sda=0;
	 _nop_();
	 _nop_();
	 _nop_();
	 _nop_();
	 scl=0;
}
void Stop()   //停止程序
{
	 sda=0;
	 scl=1;
	 _nop_();
	 _nop_();
	 _nop_();
	 _nop_();
	 sda=1;
	 _nop_();
	 _nop_();
	 _nop_();
	 _nop_();
	 scl=0;
}
void Ack()    //应答信号程序
{
	 scl=1;
	 sda=0;
	 _nop_();
	 _nop_();
	 _nop_();
	 _nop_();
	 scl=1;
	 _nop_();
	 _nop_();
	 _nop_();
	 _nop_();
	 scl=0;
}
void Nack()    //非应答信号程序
{
	 scl=1;
	 sda=1;
	 _nop_();
	 _nop_();
	 _nop_();
	 _nop_();
	 scl=1;
	 _nop_();
	 _nop_();
	 _nop_();
	 _nop_();
	 scl=0;
}
void Send(uchar Data)  //发送字节程序
{
	 uint Bitcount;
	 uchar temp;
	 for(Bitcount=0;Bitcount<8;Bitcount++)
	 {
		  temp=Data;
		  scl=0;
		  _nop_();
		  _nop_();
		  _nop_();
		  _nop_();
		  if((temp&0x80)==0x80)
		  sda=1;
		  else
		  sda=0;
		  scl=1;
		  temp=Data<<1;
		  Data=temp;
 
 	 }
 	 scl=0;
}
uchar Read(void)          //读取字节程序
{
	 uint Bitcount=8,temp=0;
	 sda=1;
	do {
		  scl=0;
		  _nop_();
		  _nop_();
		  _nop_();
		  _nop_();
		  scl=1;
		  _nop_();
		  _nop_();
		  _nop_();
		  _nop_();
		  if(sda)
		  temp=temp|0x01;
		  else
		  temp=temp&0xfe;
		  if(Bitcount-1)
		  temp=temp<<1;
		  Bitcount--;
	 }while(Bitcount);
	 return temp;
}
/*void WriteToRom(uchar Data[],uchar Add,uchar Num)  //把Data[]Num个数发送到以Add为起始地址中
{
	 uchar i;
	 uchar *PData;
	 PData=Data;
	 for(i=0;i<Num;i++)
	 {
		  Start();
		  Send(0xa0);
		  Ack();
		  Send(Add+i);
		  Ack();
		  Send(*(PData+i));
		  Ack();
		  Stop();
		  I2C_Delay(400);//延时很重要,不然就会出错
		  ////WDTRST=0x1e;
			////WDTRST=0xe1;
	 }
} */

void WriteOneByteToRom(uchar contorl,uchar Data,uchar Add)  //把Data[]Num个数发送到以Add为起始地址中
{
	Start();
	Send(contorl);
	Ack();
	Send(Add);
	Ack();
	Send(Data);
	Ack();
	Stop();
	WDTRST=0x1e;
	WDTRST=0xe1;
	I2C_Delay(800);//延时很重要,不然就会出错
	WDTRST=0x1e;
	WDTRST=0xe1;
	 
}
void ReadFromRom(uchar contorl,uchar Data[],uchar Add,uchar Num)  //读以Add为起始地址的Num个数读取到数组Data[]中
{
	 uchar i;
	 uchar *PData;
	 PData=Data;
	 for(i=0;i<Num;i++)
	 {
		  Start();
		  Send(contorl);
		  Ack();
		  Send(Add+i);
		  Ack();
		  Start();
		  Send(contorl+1);
		  Ack();
		  *(PData+i)=Read(); 
		  scl=0;
		  Nack();
		  Stop();
		  WDTRST=0x1e;
		  WDTRST=0xe1;
		  I2C_Delay(800);
		  WDTRST=0x1e;
		  WDTRST=0xe1;
	 	  
	 }
}

#endif

⌨️ 快捷键说明

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