当前位置:首页 > 单片机 > 单片机
[导读]// ****************************************************************// //------------- 虚拟 i2c软件包头文件iic.h-----------------------// //***********************************************************

// ****************************************************************//
//------------- 虚拟 i2c软件包头文件iic.h-----------------------//
//****************************************************************//

sbit SDA=P1^7; //定义IIC数据线//
sbit SCL=P1^6; //定义IIC时钟线//
#define uchar unsigned char
#define uint unsigned int
extern void delay(uint x); //延时子程序//
extern void sta(); //启动IIC总线//
extern void stop(); //停止IIC总线//
extern void mack(); //发送应答位//
extern void mnack(); //发送非应答位//
extern void cack(); //应答位检查//
extern void wrbyt(uchar shu); //发送 1 个字节//
extern viodwrbyt0();
extern void wrbyt1();
extern uchar rdbyt();//读取 1 个字节//
extern void wrnbyt(uchar slaw,uchar number,uchar ff[]);//发送N个字节//
extern void rdnbyt(uchar slar,uchar number,uchar qq[]);//读N个字节//



//************************************************************//
//---------虚拟i2c软件包,12MHz晶振----------------------//
//***********************************************************//
#pragma db cd
#i nclude
#i nclude
#i nclude



void sta() //启动iic总线//
{
SDA=1;
SCL=1;
while(SCL==0)
{;}
_nop_();
_nop_();
SDA=0;
_nop_();
_nop_();
_nop_();
_nop_();
SCL=0;
}


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


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


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


void cack()
{
SDA=1;
SCL=1;
F0=0;
if(SDA==0)
{
SCL=0;
_nop_();
_nop_();
_nop_();
_nop_();
}
else
{
F0=1;
SCL=0;
_nop_();
_nop_();
_nop_();
_nop_();
}
}




void wrbyt(uchar shu)
{
uchar i;
for(i=0;i<8;i++)
{
if ((shu&0x80)>0)
{ wrbyt1(); }
else
{ wrbyt0();}
shu<<=1;
}
}



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



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



uchar rdbyt()
{
uchar nn=0xff;
uchar j;
for (j=0;j<8;j++)
{
SDA=1;
SCL=1;
if(SDA==0)
{
nn<<=1;
nn=(nn&0xfe);
SCL=0;
}
else
{
nn<<=1;
nn=(nn|0x01);
SCL=0;
}
}
return(nn);
}







//********************写N个字节子程序************************//
//slaw--写寻址字节, number--字节数, ff[]--N个字节数组//

void wrnbyt(uchar slaw,uchar number,uchar ff[])
{
uchar idata k;
writ: do
{
sta();
wrbyt(slaw);
cack();
}while(F0==1);
for(k=0;k{
wrbyt(ff[k]);
cack();
if(F0==1)
goto writ;
}
stop();
}



//***************读N个字节子程序*********************//
//number--字节数,slar--读寻址字节,qq--贮存单元数组//

void rdnbyt(slar,number,qq)
uchar slar,number,qq[];
{
uchar idata data0,l;
do
{
sta();
wrbyt(slar);
cack();
}while(F0==1);

for(l=0;l{
data0=rdbyt();
qq[l]=data0;
if(l<(number-1))
{ mack(); }
}
mnack();
stop();
}

本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除( 邮箱:macysun@21ic.com )。
换一批
延伸阅读
关闭