1、18B20.H代码
#ifndef __DS18B20_H__
#define __DS18B20_H__
#include "REG51.H"
#include "string.h"
#include "intrins.H"
#include "stdio.h"
#include"delay.h"
#define uchar unsigned char
#define uint unsigned int
sbit DS = P0^3;
extern unsigned int TEMP;
void delay_us(uchar us);
//void Delay1000ms(); //@11.0592MHz
void DS18B20_init();
void DSWriteByte(uchar dat); //总线每次只能写一位进去
uchar DSReadByte();
void DS18B20_Read();
#endif
2、18B20.C代码
#include "ds18b20.h"
unsigned int TEMP=0;
void delay_us(uchar us)
{
while(us--);
}
void DS18B20_init()
{
DS = 1;
_nop_();
DS = 0;
delay_us(80);
DS = 1;
delay_us(7);
while(0 == DS);
DS = 1;
}
//写一个字节
void DSWriteByte(uchar dat) //总线每次只能写一位进去
{
uchar i;
for(i = 0;i<8;i++)
{
DS = 0; //下拉总线
_nop_(); //产生一点时序
DS = dat & 0x01; //0x01 00000001
delay_us(10); //76.95us
DS = 1; //上拉总线
_nop_();
dat >>= 1; //dat右移一位
}
}
//读一个字节
uchar DSReadByte()
{
unsigned char i,j,dat;
for(i=0;i<8;i++)
{
DS = 0;
_nop_();
DS = 1;
j = DS;
_nop_();
_nop_();;
dat = (dat>>1)|(j<<7);
delay_us(5);
DS = 1;
}
return dat;
}
void DS18B20_Read()
{
uchar L,M,bai,shi,ge;
uint i;
DS18B20_init(); //初始化
delay_us(10);
DSWriteByte(0xcc); //发送忽略ROM指令
DSWriteByte(0x44); //发送完指令后,DS18B20开始转换并且存储到高速寄存器
DS18B20_init();
delay_us(10);
DSWriteByte(0xcc); //发送忽略ROM指令
DSWriteByte(0xbe); //读取DS18B20暂存器指令
L = DSReadByte(); //读取LS BYTE
M = DSReadByte(); //读取MS BYTE
i = M;
i <<=8;
i = i|L; //效果为 假设M为00000111 左移八位变为 0000011100000000(<<自动补全0)然后或上L,相当于M+L
i = i*0.0625*100+0.5; //+0.5 为了四舍五入。因为if为int型,自动抛掉小数点后面
bai = (i / 10000);
shi = (i % 10000/1000);
ge = (i % 1000/100);
TEMP=shi*10+ge;
}