用51单片机设计一个基于ds18b20的温度检测的系统
时间: 2023-10-06 20:06:04 浏览: 79
好的,下面是基于51单片机设计的基于DS18B20的温度检测系统的步骤:
1. 硬件连接:将DS18B20传感器的VCC引脚连接到单片机的5V电源,GND引脚连接到单片机的地,DATA引脚连接到单片机的P1.0引脚。
2. 程序设计:
首先,需要定义DS18B20传感器的一些命令和参数,例如初始化命令、读取温度值命令等。
然后,需要进行DS18B20传感器的初始化,包括发送初始化命令、检测传感器是否存在等操作。
接着,需要发送读取温度值命令,并读取传感器返回的温度值,进行解析和计算,得到温度值。
最后,将温度值显示在LCD屏幕或其他输出设备上。
具体的程序实现可以参考以下代码:
```
#include <reg52.h>
#include <intrins.h>
typedef unsigned char uint8;
typedef unsigned int uint16;
#define DS18B20_DQ P1_0
void Delay_1us(uint16 n)
{
while(n--)
{
_nop_();
_nop_();
}
}
uint8 DS18B20_Init()
{
uint8 i;
DS18B20_DQ = 1;
Delay_1us(1);
DS18B20_DQ = 0;
Delay_1us(500);
DS18B20_DQ = 1;
Delay_1us(60);
i = DS18B20_DQ;
Delay_1us(240);
return i;
}
void DS18B20_WriteByte(uint8 dat)
{
uint8 i;
for(i = 0; i < 8; i++)
{
DS18B20_DQ = 0;
Delay_1us(2);
DS18B20_DQ = dat & 0x01;
dat >>= 1;
Delay_1us(60);
DS18B20_DQ = 1;
}
}
uint8 DS18B20_ReadByte()
{
uint8 i, dat = 0;
for(i = 0; i < 8; i++)
{
DS18B20_DQ = 0;
Delay_1us(2);
DS18B20_DQ = 1;
Delay_1us(5);
dat |= DS18B20_DQ << i;
Delay_1us(53);
}
return dat;
}
float DS18B20_GetTemp()
{
uint8 TL, TH;
float temp;
DS18B20_Init();
DS18B20_WriteByte(0xcc);
DS18B20_WriteByte(0x44);
Delay_1us(100);
DS18B20_Init();
DS18B20_WriteByte(0xcc);
DS18B20_WriteByte(0xbe);
TL = DS18B20_ReadByte();
TH = DS18B20_ReadByte();
temp = TH;
temp *= 256;
temp += TL;
temp *= 0.0625;
return temp;
}
void main()
{
float temp;
uint8 temp_int, temp_float;
while(1)
{
temp = DS18B20_GetTemp();
temp_int = (uint8)temp;
temp_float = (uint8)((temp - temp_int) * 10);
//显示温度值,这里使用LCD1602屏幕
//具体的LCD1602显示程序这里不再给出
LCD1602_WriteByte(temp_int + '0');
LCD1602_WriteByte('.');
LCD1602_WriteByte(temp_float + '0');
LCD1602_WriteByte('C');
Delay_1ms(1000);
}
}
```
以上代码是一个简单的DS18B20温度检测程序,可以通过LCD1602屏幕显示温度值。需要注意的是,程序中使用了一些延时函数,这些函数需要根据实际情况进行调整。同时,还需要根据实际硬件电路进行一些修改,例如修改GPIO引脚的定义等。