基于51单片机的DS18B20,编写程序,调试完成测温实验,要求用LED1602显示。第一行显示503,第二行显示温度
时间: 2023-12-07 19:04:31 浏览: 23
好的,您需要进行以下步骤:
1. 将DS18B20温度传感器连接到51单片机上,并编写相应的读取温度数据的程序。
2. 将LED1602液晶屏连接到51单片机上,并编写相应的显示程序。
下面是一个简单的示例程序,供您参考:
```
#include <reg52.h>
#include <intrins.h>
#define LCD_RW P2_1
#define LCD_RS P2_0
#define LCD_E P2_2
sbit DQ = P3^7;
unsigned char temp[5];
void delay(unsigned int t)
{
while(t--);
}
void InitLCD()
{
delay(200);
LCD_RS = 0;
LCD_RW = 0;
LCD_E = 0;
delay(200);
LCD_RS = 0;
LCD_RW = 0;
LCD_E = 1;
P0 = 0x38; // function set: 8-bit, 2-line, 5x8 dots
LCD_E = 0;
delay(200);
LCD_RS = 0;
LCD_RW = 0;
LCD_E = 1;
P0 = 0x0c; // display control: display on, cursor off, blink off
LCD_E = 0;
delay(200);
LCD_RS = 0;
LCD_RW = 0;
LCD_E = 1;
P0 = 0x01; // clear display
LCD_E = 0;
delay(200);
LCD_RS = 0;
LCD_RW = 0;
LCD_E = 1;
P0 = 0x06; // entry mode set: increment, no shift
LCD_E = 0;
}
void WriteLCD(unsigned char dat, unsigned char cmd)
{
LCD_RS = cmd;
LCD_RW = 0;
LCD_E = 1;
P0 = dat;
LCD_E = 0;
}
void WriteTemp()
{
unsigned char i;
WriteLCD(0x80, 0); // set cursor to first line
for(i=0; i<3; i++)
{
WriteLCD(temp[i], 1); // write temperature value
}
WriteLCD('C', 1); // write temperature unit
}
unsigned char ReadTemp()
{
unsigned char i, j;
unsigned char temp_l, temp_h;
unsigned char flag;
DQ = 1;
_nop_();
_nop_();
DQ = 0;
_nop_();
_nop_();
_nop_();
_nop_();
DQ = 1;
_nop_();
_nop_();
flag = DQ;
_nop_();
_nop_();
_nop_();
_nop_();
for(i=0; i<8; i++)
{
DQ = 0;
_nop_();
_nop_();
_nop_();
temp_l >>= 1;
if(DQ)
temp_l |= 0x80;
DQ = 1;
_nop_();
_nop_();
_nop_();
temp_h >>= 1;
if(DQ)
temp_h |= 0x80;
_nop_();
}
if(flag)
{
temp_h = ~temp_h;
temp_l = ~temp_l;
}
j = temp_h >> 4;
temp[0] = j / 10 + '0';
temp[1] = j % 10 + '0';
temp[2] = '.';
j = temp_h & 0x0f;
temp[3] = j * 625 / 1000 + '0';
temp[4] = '\0';
return temp_h;
}
void main()
{
unsigned char t;
InitLCD();
while(1)
{
t = ReadTemp();
WriteTemp();
delay(1000);
}
}
```
需要注意的是,该程序仅供参考,您需要根据实际情况进行修改。此外,您还需要在程序中加入对DS18B20传感器的初始化和读取温度数据的代码。