此次编写的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);
}