在开头说明一下:本程序只用了温度测量这一个功能,其他功能并未在此涉及。 鄙人不才,如有错误还望各位大佬指点。 趁这段时间充裕把DS18B20温度传感器的一些东西写一写(主要是程序)。 Dallas半导体公司的数字化温度传感器DS18B20是世界上第一片支持“一线总线”接口的温度传感器,即只有一根数据线。它的适用电压为3V-5V,可程序设定9-12位的分辨率,精度为±0.5℃,测温范围-55℃~+125℃。 DS18B20的使用难点主要在延时时间上,只要把延时搞懂了那么除测温以外的功能也就不难了。相信你们手里都有芯片手册,手册上的时序画的明明白白,我也就不多说废话了,直接上程序
/**************************************
平台STC89C52 晶振11.0592MHz
6位共阴数码管 74HC573锁存器
**************************************/
#include
#include
#define uchar unsigned char
#define uint unsigned int
uchar code table[]={0x3f,0x06,0x5b,0x4f,0x66,
0x6d,0x7d,0x07,0x7f,0x6f, ///不带小数点0~9
0xbf,0x86,0xdb,0xcf,0xe6,
0xed,0xfd,0x87,0xff,0xef, ///带小数点0~9
0x40,0x00};
uchar tem[2]; ///用来存放两字节的温度
uchar wendu[5]; ///用来存放(正负)十进制的温度
uchar fuhao;
bit flag;
sbit DQ=P2^2; ///传感器的信号线
sbit dula=P2^6; ///数码管段选端
sbit wela=P2^7; ///数码管位选端
void delayus(uchar t)
{
while(t--);
}
void delayms(uint z)
{
uint i,j;
for(i=z;i>0;i--)
for(j=110;j>0;j--);
}
void delaynop()
{
_nop_();
}
/***************************************
DS18B20复位函数
***************************************/
void res()
{
DQ=1;
_nop_();
_nop_();
_nop_();
DQ=0;
delayus(90); ///约600us
DQ=1;
delayus(9); ///约70us
flag=DQ; ///若flag为0则复位成功,否则失败
delayus(80); ///约530us
DQ=1;
_nop_();
}
/*************************************
写一个字节函数
*************************************/
void ds18b20_write_byte(uchar dat)
{
uchar i;
bit j;
for(i=8;i>0;i--)
{
j=dat&0x01;
dat=dat>>1;
DQ=1;
_nop_();
if(j==0)
{
DQ=0;
delayus(9); ///约70us
DQ=1;
_nop_();
}
else
{
DQ=0;
_nop_();
_nop_();
_nop_();
DQ=1;
delayus(9);
}
}
}
/************************************
读一个字节函数
************************************/
bit ds18b20_read_bit()
{
bit j;
DQ=1;
_nop_();
DQ=0;
delaynop();
DQ=1;
_nop_();
j=DQ;
delayus(8);
DQ=1;
_nop_();
return j;
}
uchar ds18b20_read_byte()
{
uchar i,j,dat;
for(i=8;i>0;i--)
{
j=ds18b20_read_bit();
dat=(dat>>1)|(j |