📄 ds18b20.c
字号:
#include "reg52.h"
#include <intrins.h>
#define Ds18b20 1
#define Standard 1
#define uint unsigned int
#define uchar unsigned char
#define Clock 12//18.324
//18.324M
#define D_D 4*Clock/8
#define A 6*Clock/8
#define B 64*Clock/8
#define C 60*Clock/8
#define D 10*Clock/8
#define E 4*Clock/8
#define F 55*Clock/8
#define G 0*Clock/8
#define H 480*Clock/8
#define I 70*Clock/8
#define J 410*Clock/8
sbit DQ=P2^2;
sbit test=P2^3;
void Delay(uint a) //8个state
{
while(a)
a--;
}
void WriteBit(bit Num)
{ //EA=0;
if (Num)
{
// Write '1' bit
DQ=0; // Drives DQ low
Delay(D_D);
DQ=1; // Releases the bus
Delay(B); // Complete the time slot and 10us recovery
}
else
{
// Write '0' bit
DQ=0; // Drives DQ low
Delay(C);
DQ=1; // Releases the bus
Delay(D);
}
//EA=1;
}
bit Reset(void)
{
bit result;
//EA=0;
Delay(G);
DQ=0; // Drives DQ low
Delay(H);
DQ=1; // Releases the bus
Delay(I);
result= DQ; // Sample for presence pulse from slave
Delay(J); // Complete the reset sequence recovery
DQ=1;
//EA=1;
return result; // Return sample presence pulse result
}
/*bit ReadBit(void)
{
bit result;
DQ=0; // Drives DQ low
Delay(A);
//DQ=1; // Releases the bus
P1M1|=0x1;
//P1M2=0;
Delay(E);
result= DQ; // Sample the bit value from the slave
Delay(F); // Complete the time slot and 10us recovery
P1M1&=0xfe;
DQ=1;
return result;
}
*/
bit ReadBit(void)
{
bit result;
//EA=0;
DQ=0; // Drives DQ low
Delay(D_D);
DQ=1; // Releases the bus
Delay(D_D); result= DQ; // Sample the bit value from the slave
Delay(F); // Complete the time slot and 10us recovery
//EA=1;
return result;
}
void WriteByte(uchar databuf)
{
uchar loop;
for (loop = 0; loop < 8; loop++)
{
WriteBit(databuf & 0x01);
databuf >>= 1;
}
}
uchar ReadByte(void)
{
uchar loop, result=0;
for (loop = 0; loop < 8; loop++)
{
result >>= 1;
if (ReadBit())
result |= 0x80;
}
return result;
}
struct Page0{
uchar Teml;
char Temh;
uchar Voll;
uchar Volh;
uint Cur;
uchar ThresHold;
uchar CrcCode;
uchar state;
};
struct Page0 idata *PPage0;
uchar data page_data[9];
uint VolValue,CurValue,IntTemValue;
float TemValue;
uchar ICA;
uchar ReadPage()
{
uchar i;
if (Reset()) // Reset the 1-Wire bus
return 0; // Return if no devices found
WriteByte(0xcc);
WriteByte(0x44);
while(!ReadBit());
Reset();
WriteByte(0xcc);
WriteByte(0xbe);
// read the page data
for (i = 0; i <9; i++)
page_data[i] = ReadByte();
Reset();
PPage0=(struct Page0 idata *)page_data;
if(PPage0->Temh<0)
{
IntTemValue=PPage0->Temh*(-1)*0x100+PPage0->Teml;//PPage0->Teml&0x1f*0.0625; //PPage0->Temh*(-1)+(float)(PPage0->Teml>>=4)*0.125;
TemValue=(IntTemValue%16)*0.0625+IntTemValue/16;
}
else
{
IntTemValue=PPage0->Temh*0x100+PPage0->Teml;
TemValue=(IntTemValue%16)*0.0625+IntTemValue/16;
}
if (Reset()) // Reset the 1-Wire bus
return 0;
return 1;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -