|
i2c虚拟总线通用软件包(qinguoxi)
飞飞 发表于 2006-3-21 18:15:51
// ****************************************************************// //------------- 虚拟 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 viod wrbyt0(); 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 <intrins.h> #i nclude <reg51.h> #i nclude<iic.h>
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<number;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<number;l++) { data0=rdbyt(); qq[l]=data0; if(l<(number-1)) { mack(); } } mnack(); stop(); }
|