51单片机Ds18b20温度传感器程序
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
* 实验名 : 18B20温度显示试验
* 实验说明 : 数码管显示温度值,并且将温度值通过串口发送到电脑上。* 连接方式 : 见连接图
temp.h
#ifndef __TEMP_H_
#define __TEMP_H_
#include
//---重定义关键词---//
#ifndef uchar
#define uchar unsigned char
#endif
#ifndef uint
#define uint unsigned int
#endif
//--定义使用的IO口--//
sbit DSPORT=P3^7;
//--声明全局函数--//
void Delay1ms(uint );
uchar Ds18b20Init();
void Ds18b20WriteByte(uchar com);
uchar Ds18b20ReadByte();
void Ds18b20ChangTemp();
void Ds18b20ReadTempCom();
int Ds18b20ReadTemp();
#endif
temp.c
#include"temp.h"
/*******************************************************************************
* 函数名: Delay1ms
* 函数功能: 延时函数
* 输入: 无
* 输出: 无
*******************************************************************************/
void Delay1ms(uint y)
{
uint x;
for( ; y>0; y--)
{
for(x=110; x>0; x--);
}
}
/*******************************************************************************
* 函数名: Ds18b20Init
* 函数功能: 初始化
* 输入: 无
* 输出: 初始化成功返回1,失败返回0
*******************************************************************************/ uchar Ds18b20Init()
{
uchar i;
DSPORT = 0;//将总线拉低480us~960us
i = 70;
while(i--);//延时642us
DSPORT = 1;//然后拉高总线,如果DS18B20做出反应会将在15us~60us后总线拉低
i = 0;
while(DSPORT)//等待DS18B20拉低总线
{
Delay1ms(1);
i++;
if(i>5)//等待>5MS
{
return 0;//初始化失败
}
}
return 1;//初始化成功
}
/*******************************************************************************
* 函数名: Ds18b20WriteByte
* 函数功能: 向18B20写入一个字节
* 输入: com
* 输出: 无
*******************************************************************************/
void Ds18b20WriteByte(uchar dat)
{
uint i, j;
for(j=0; j<8; j++)
{
DSPORT = 0;//每写入一位数据之前先把总线拉低1us
i++;
DSPORT = dat & 0x01; //然后写入一个数据,从最低位开始
i=6;
while(i--); //延时68us,持续时间最少60us
DSPORT = 1;//然后释放总线,至少1us给总线恢复时间才能接着写入第二个数值
dat >>= 1;
}
}
/*******************************************************************************
* 函数名: Ds18b20ReadByte
* 函数功能: 读取一个字节
* 输入: com
* 输出: 无
*******************************************************************************/ uchar Ds18b20ReadByte()
{
uchar byte, bi;
uint i, j;
for(j=8; j>0; j--)
{
DSPORT = 0;//先将总线拉低1us
i++;
DSPORT = 1;//然后释放总线
i++;