送上1-w总线读写函数。
PIC采用4M晶体,所有的延时经过严格调试,修改要小心!!#define false 0
#define true1
#define uchar unsigned char
#define uintunsigned int
#define boolunsigned char
#define ulong unsigned long
#define Hi 1
#define Low 0
#define DQ RA4
#define SetDQ TRISA4
void delay(unsigned int val){
while(val--);
}
bool OWReset(){
unsigned char presence;
unsigned char i=2;
SetDQ=Hi;
SetDQ=Low; //设定TRIS来控制总线高低,这是PIC独特的形式
DQ=0; //刷新PORT,避免干扰
delay(42);//480us
SetDQ=Hi;
while(--i);//7us
if(!DQ)
i=1; //7us后检测总线,正常情况下总线不可能为低。
delay(4);//61us
presence=DQ;
delay(35);//400us
if(i || presence)
return false;
return true;
}
bool OWReadBit(){
unsigned char sampling=2;
SetDQ=Low;
while(--sampling);
SetDQ=Hi;
sampling=0;
NOP();NOP();NOP();NOP();
if(DQ)sampling++; //10us后连续3次采样总线
if(DQ)sampling++;
if(DQ)sampling++;
delay(4);//60us
if(sampling>=2) //采3取2,提高可靠性
return 1;
return 0;
}
unsigned char OWReadByte(){
unsigned char i;
unsigned char val=0;
for(i=8;i!=0;i--){
val>>=1;
if(OWReadBit())
val|=0x80; //最接近汇编的写法
}
return val;
}
bool OWWriteBit(bool bitval){
unsigned char sampling=0;
SetDQ=Low;
NOP();NOP();
if(bitval&0x01)
SetDQ=Hi;
NOP();NOP();NOP();NOP();
if(DQ)sampling++;
NOP();NOP();NOP();NOP();
if(DQ)sampling++;
NOP();NOP();NOP();NOP();
if(DQ)sampling++; //采3取2来判断总线状态是否和写位一致,如果有干扰或短路
//可以及时检查出。
delay(2);
sampling=(sampling>=2);
SetDQ=Hi;
if(sampling==bitval)
return true;
return false;
}
bool OWWriteByte(unsigned char val){
unsigned char i;
for(i=8;i!=0;i--){
if(!OWWriteBit(val&0x01))
return false;
val>>=1;
}
return true;
}
页:
[1]