//This souce file includes the basic one wire operation functions: delayow, write bit, read bit, write byte, read byte;
//resetpresense, CRC8 check, CRC16 check.
//This functions are called by other routines.
//#include "SYS.H"
#include "PORT.H"
#include "c8051f020.h"
#include <absacc.h>
sbit DQ = P1^2;
//The following is the function prototypes
void delayow(uint16);
void writebit(uint8);
uint8 readbit();
void writebyte(uint8);
uint8 readbyte();
uint8 restpresnese();
//The following is the function body
//Delay function, the unit delay is about 10uS
void delayow(uint16 us)
{
uint16 idata i;
for (i = 0; i <= us; i++) {
}
}
//Resetpresense function
uint8 rest()
{
uint8 idata pre;
DQ = 0; //DQ is the ow data/power line defined in sys.h.
delayow(500); //Delay for the reset pulse.
DQ = 1; //Release the line so that the slave can drive the line low after a while.
delayow(60); //Delay for the slave to drive the line low.
pre = (uint8)DQ;
delayow(480); //Delay for the slave to release the line.
DQ = 1; //Host drive the line high.
return pre;
}
//Write bit
void writebit(uint8 sendbit)
{
DQ = 0;
delayow(2); //Delay for the leading signal.
if (sendbit == 0x01) { //If the send bit is 1 then release the line.
DQ = 1;
}
delayow(80); //Delay for the 1 wire device to sample the line.
DQ = 1; //Release the line to be in idle state.
delayow(10); //Delay for recovery time.
return;
}
//Read bit
uint8 readbit()
{
uint8 idata readbit;
DQ = 0;
delayow(2); //Delay for the leading signal.
DQ = 1; //Host "release" the line.
delayow(10); //Delay for the data put on the line by slave to be stable.
readbit = (uint8)DQ;
delayow(70); //delayoe for the slave to release the line, including the recoery time.
DQ = 1; //Host "forces" the line to be in idle state.
return readbit;
}
//Write byte
void writebyte(uint8 senddata)
{
uint8 idata i;
uint8 idata temp;
for (i = 0x00; i <= 0x07; i++) {
temp = senddata >> i; //The data to be send is right shifted to the right most position of the byte according to the real position
writebit(temp & 0x01); //of the data, and the data is "and" with 0x01, to determine if the send data is 0 or 1.
}
}
//Read byte
uint8 Readbyte()
{
uint8 idata readdata = 0x00; //The readdata is initialised to 0x00.
uint16 idata setcontrol = 0x0001; //The setcontrol is initialised to 0x0001,and will be shifted left when each time reading a bit.
while (setcontrol <= 0x0080) { //Why using uint16 instead of uint8?If use uint8, what will happen after left shifting 0x80? It depends on
if (readbit()) { //machine implementation.So for portable purpose we use uint16.
readdata = readdata | setcontrol;//If the read bit is 1 then readdata is "or" with setcontrol and store back to readdata.
}
setcontrol = setcontrol << 1; //Left shift the setcontrol.
}
return readdata;
}
评论2