#include<reg52.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
#define MASK 0x01
sbit DS18B20 = P3^7;
//sbit lcden = P2^7;
//sbit lcdrs = P2^6;
//sbit lcdrw = P2^5;
//uchar code table[]={0,0,1,2,2,3,4,4,5,6,6,7,8,8,9,9};
void Config18b20(void);
bit Reset(void);
void write_byte(uchar temp);
uchar read_byte(void);
bit read_temper(uchar * ls, uchar * ms);
void delay60us(uint i);
void delay5us(void);
int main(void)
{
uchar ls = 0,ms = 0,temp;
Config18b20();
while(1)
{
if(read_temper(&ls,&ms))
{
temp = ls & 0x0f;
P1 = temp; // 用来测试是否读取成功
delay60us(50);
}
else
P1 = 0x00;
}
}
void Config18b20(void) //重新配置报警限定值和分辨率
{
Reset();
write_byte(0xcc); //skip rom
write_byte(0x4e); //write scratchpad
write_byte(0x23); //上限
write_byte(0x0f); //下限
write_byte(0x7f); //set 12 bit (0.125)
Reset();
write_byte(0xcc); //skip rom
write_byte(0x48); //保存设定值
Reset();
write_byte(0xcc); //skip rom
write_byte(0xb8); //回调设定值
}
bit Reset(void)
{
bit flag = 1;
DS18B20 = 1;
_nop_();
DS18B20 = 0;
delay60us(10);
DS18B20 = 1;
delay60us(1);
delay5us();
flag = DS18B20;
delay60us(9);
DS18B20 = 1;
delay60us(20);
return flag;
}
void write_byte(uchar temp)
{
uchar i;
DS18B20 = 1;
_nop_();
for(i = 0; i < 8; i++)
{
DS18B20 = 0;
delay5us();
DS18B20 = (temp >> i) & MASK;
delay60us(1);
DS18B20 = 1;
_nop_();
}
}
uchar read_byte(void)
{
uchar i,temp;
DS18B20 = 1;
_nop_();
for(i = 0; i < 8; i++)
{
DS18B20 = 0;
_nop_();
_nop_();
DS18B20 = 1;
delay5us();
temp >>= 1;
if(DS18B20)
temp |= 0x80;
delay60us(1);
}
return temp;
}
bit read_temper(uchar * ls, uchar * ms)
{
bit k = 0;
if(!Reset())
{
write_byte(0xcc);
write_byte(0x44);
while(!DS18B20); // 等待转换换成
}
if(!Reset())
{
write_byte(0xcc);
write_byte(0xbe);
*ls = read_byte();
*ms = read_byte();
k = 1;
}
return k;
}
void delay60us(uint i)
{
uchar j;
for(i; i > 0; i--)
for(j = 0; j < 15; j++)
continue;
}
void delay5us(void)
{
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
|