I2C

此次编写的I2C程序是利用模拟的I2C接口,只要模拟实际I2C的时序,就可以进行操作,但是实际的比模拟的难调一些,利用I2C可以读EPROM进行读写操作代码如下:
#include <reg52.h>
#include <intrins.h>
#define	uchar unsigned char
#define uint unsigned int
sbit SCL=P2^1;
sbit SDA=P2^0;
//sbit rs=P2^0;
//sbit rw=P2^1;
//sbit en=P2^2;

//void delay(void)   //误差 0us
//{
//   	_nop_(); 
//    _nop_();  //if Keil,require use intrins.h
//	_nop_(); 
//	_nop_(); 
//	_nop_();  
//}

//void delay1(void)   //误差 0us
//{
//    unsigned char a,b,c;
//    for(c=1;c>0;c--)
//        for(b=142;b>0;b--)
//            for(a=2;a>0;a--);
//}

void start(void)
{
	SDA=1;
	_nop_();
	_nop_();
	SCL=1;
	_nop_();
	_nop_();
	_nop_();
	_nop_();
	_nop_();
	SDA=0;
	_nop_();
	_nop_();
	_nop_();
	_nop_();
	_nop_();
	SCL=0;
	_nop_();
	_nop_();	
}

void stop(void)
{
	SDA=0;
	_nop_();
	_nop_();
	SCL=1;
	_nop_();
	_nop_();
	_nop_();
	_nop_();
	_nop_();
	SDA=1;
	_nop_();
	_nop_();
	_nop_();
	_nop_();
}

void ack(bit a)
{
  
  if(a==0)SDA=0;              /*在此发出应答或非应答信号 */
  else SDA=1;
  _nop_();
  _nop_();
  _nop_();    
  SCL=1;
  _nop_();
  _nop_();
  _nop_();
  _nop_();
  _nop_(); 
  SCL=0;                     /*清时钟线,钳住I2C总线以便继续接收*/
  _nop_();
  _nop_();     
}

//void init(void)
//{
//	SDA=1;
//	SCL=1;
//}

void cwr_byte(uchar dat)
{
	uchar i,ack;
	for(i=0;i<8;i++)
	{
		if(dat&0x80)
		{
			SDA=1;
		}
		else 
		{
			SDA=0;
		}
		dat=dat<<1;
		_nop_();
		_nop_();
		SCL=1;
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		SCL=0;
	}
		_nop_();
		_nop_();
		SDA=1;
		_nop_();
		_nop_();
		SCL=1;
		_nop_();
		_nop_();
		_nop_();
		if(SDA==1)ack=0;     
   else ack=1;        /*判断是否接收到应答信号*/
    	SCL=0;
    	_nop_();
		_nop_();

}

uchar cre_byte(void)
{
	uchar i,dat;
	SDA=1;
	for(i=0;i<8;i++)
	{
		_nop_();
		SCL=0;
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		_nop_();
		SCL=1;
		_nop_();
		_nop_();
		dat=dat<<1;
		if(SDA)
		{
			dat++;
		}
		_nop_();
		_nop_();
	}
	SCL=0;
	_nop_();
	_nop_();
	return dat;	
}
uint write_byte(uint add,uint shu)
{
	start();
	cwr_byte(0xa0);
	if(ack==0)return(0);
	cwr_byte(add);
	if(ack==0)return(0);
//	cwr_byte(0XFF);
//	ack();
	cwr_byte(shu);
	if(ack==0)return(0);
	stop();
	return(1);

}
uint read_byte(uint add)
{
	uint a;
	start();
	cwr_byte(0xa0);
	if(ack==0)return(0);
	cwr_byte(add);
	if(ack==0)return(0);
//	cwr_byte(0XFF);
//	ack();
	start();
	cwr_byte(0xa1);
	if(ack==0)return(0);
	a=cre_byte();
	ack(1);
	stop();
//	return(1);
	return a;
}
void main()
{
	write_byte(9,0x55);
	P1=read_byte(9);


}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值