基于51的DS18B20温度传感器,通过LCD1602显示代码
时间: 2024-02-22 16:59:28 浏览: 26
下面是基于51单片机控制DS18B20温度传感器,并通过LCD1602显示温度值的代码示例:
```c
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit DQ = P1^5; // DS18B20数据引脚
sbit RS = P2^5; // LCD1602 RS引脚
sbit RW = P2^6; // LCD1602 RW引脚
sbit EN = P2^7; // LCD1602 EN引脚
uchar code table[] = "Temperature:"; // LCD1602显示字符串
// 初始化DS18B20
uchar Init_DS18B20()
{
uchar i;
DQ = 1;
for (i = 0; i < 50; i++); // 等待485总线稳定
DQ = 0;
for (i = 0; i < 50; i++); // 拉低总线480us
DQ = 1;
for (i = 0; i < 5; i++)
{
if (!DQ) // 等待DS18B20响应
{
return 0;
}
for (i = 0; i < 50; i++); // 等待60us
}
return 1;
}
// 读取DS18B20温度值
void Read_DS18B20(uchar *temp)
{
uchar i, j;
Init_DS18B20();
DQ = 0;
for (i = 0; i < 5; i++); // 拉低总线后等待一段时间
DQ = 1;
for (i = 0; i < 50; i++); // 等待DS18B20响应
if (!DQ) // 如果DS18B20响应
{
for (i = 0; i < 8; i++)
{
DQ = 0;
for (j = 0; j < 5; j++); // 等待60us
DQ = 1;
for (j = 0; j < 50; j++); // 等待读取温度值
temp[i] = DQ; // 读取温度值
}
}
}
// 写命令到LCD1602
void Write_Cmd(uchar cmd)
{
RW = 0; // 写入模式
RS = 0; // 命令模式
P0 = cmd; // 写入命令
EN = 1; // 使能
for (uint i = 0; i < 100; i++); // 延时
EN = 0; // 失能
}
// 写数据到LCD1602
void Write_Data(uchar dat)
{
RW = 0; // 写入模式
RS = 1; // 数据模式
P0 = dat; // 写入数据
EN = 1; // 使能
for (uint i = 0; i < 100; i++); // 延时
EN = 0; // 失能
}
// 初始化LCD1602
void Init_LCD1602()
{
Write_Cmd(0x38); // 初始化LCD1602,设置为8位数据接口、双行显示、5x7点阵字符
Write_Cmd(0x0c); // 开启显示,关闭光标
Write_Cmd(0x06); // 设置光标移动方向
Write_Cmd(0x01); // 清屏
}
// 在LCD1602上显示温度值
void Display_Temperature(uchar *temp)
{
uchar i;
Init_LCD1602(); // 初始化LCD1602
for (i = 0; i < 12; i++) // 显示字符串
{
Write_Data(table[i]);
}
for (i = 0; i < 8; i++) // 显示温度值
{
Write_Data(temp[i] + '0');
}
}
// 主函数
void main()
{
uchar temp[8]; // 存储温度值
Read_DS18B20(temp); // 读取温度值
Display_Temperature(temp); // 在LCD1602上显示温度值
while (1); // 程序循环
}
```
这段代码实现了DS18B20温度传感器的初始化和读取,并将温度值显示在LCD1602上。需要注意的是,具体的引脚连接方式需要根据自己的硬件环境进行修改。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)