📄 ds18b20.c
字号:
#include <intrins.h>
#include <reg51.h>
//这里以11.0592M晶体为例,不同的晶体速度可能需要调整延时的时间
sbit DQ = P3^5;
unsigned char m_CRC(unsigned char CRC0,unsigned char InByt);
//延时
void delay(unsigned int useconds)
{
for(;useconds>0;useconds--);
}
void delay750()
{
int x;
for(x=0;x<20000;x++) {}
for(x=0;x<20000;x++) {}
for(x=0;x<20000;x++) {}
for(x=0;x<20000;x++) {}
for(x=0;x<20000;x++) {}
for(x=0;x<20000;x++) {}
for(x=0;x<20000;x++) {}
for(x=0;x<20000;x++) {}
}
//复位
bit ow_reset(void) // 0=presence, 1 = no part
{
bit presence;
char count;
DQ = 0; //pull DQ line low
delay(42); // leave it low for 480us
DQ = 1; // allow line to return high
count = 0;
delay(2);
do
{
delay(1); // the first is for recover period
presence = DQ;
count++;
} while (presence && (count<8));
if(count>=8) return 1;
count = 0;
do
{
delay(1);
presence = DQ;
count++;
} while (!presence&&(count<60));
if(count>=60) return 1; // 如果拉死,也认为不存在
delay(36);
return 0;
}
//从 1-wire 总线上读取一个字节
unsigned char read_byte(void)
{
unsigned char i;
unsigned char value = 0;
for (i=8;i>0;i--)
{
value>>=1;
DQ = 0; // pull DQ low to start timeslot
DQ = 0; // then return high
DQ = 1; // then return high
DQ = 1; // then return high
//
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
if(DQ)value|=0x80;
delay(4); // wait for rest of timeslot
}
return(value);
}
//向 1-WIRE 总线上写一个字节
void write_byte(char val)
{
unsigned char i;
for (i=8; i>0; i--) // writes byte, one bit at a time
{
DQ = 0; // pull DQ low to start timeslot
DQ = 0; //pull DQ line low
DQ = val&0x01;
delay(5); // hold value for remainder of timeslot
DQ = 1;
val=val/2;
}
delay(5);
}
//读取温度
int Read_Temperature(void)
{
unsigned char xl,xh;
unsigned char cfg;
unsigned int x;
unsigned char crc;
do
{
ow_reset();
write_byte(0xCC); // Skip ROM
write_byte(0x44); // Start Conversion
delay(2);
delay750();
ow_reset();
write_byte(0xCC); // Skip ROM
write_byte(0xBE); // Read Scratch Pad
xl = read_byte();
crc = m_CRC(0,xl);
xh = read_byte();
crc = m_CRC(crc,xh);
cfg = read_byte(); // TH
crc = m_CRC(crc,cfg);
cfg = read_byte(); // TL
crc = m_CRC(crc,cfg);
cfg = read_byte(); // config
crc = m_CRC(crc,cfg);
cfg = read_byte(); // Reserve0
crc = m_CRC(crc,cfg);
cfg = read_byte(); // Reserve1
crc = m_CRC(crc,cfg);
cfg = read_byte(); // Reserve2
crc = m_CRC(crc,cfg);
cfg = read_byte(); // CRC read from inside
} while(cfg!=crc);
// ow_reset();
x = xh;
x = (x<<8)+xl + 3; // 4 舍 5 入
x = (x>>3);
x = x + (x<<2);
// x = cfg;
return x;
}
int Read_ROM(char k)
{
unsigned char x[8];
char i;
ow_reset();
write_byte(0x33); // Skip ROM
for(i = 0;i<8;i++) x[i] = read_byte();
ow_reset();
return x[k];
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -