51单片机lcd1602显示温度
时间: 2023-08-31 22:12:53 浏览: 114
基于51单片机的DS18B20下的LCD1602.rar
以下是51单片机LCD1602显示温度的代码示例:
```c
#include <reg51.h>
#include <stdio.h>
#define LCD_RS P2_0
#define LCD_RW P2_1
#define LCD_E P2_2
#define LCD_DAT P0
void delay(unsigned int t) //延时函数
{
unsigned int i, j;
for (i = t; i > 0; i--)
for (j = 10; j > 0; j--);
}
void lcd_write_cmd(unsigned char cmd) //写命令
{
LCD_RS = 0;
LCD_RW = 0;
LCD_DAT = cmd;
delay(5);
LCD_E = 1;
delay(5);
LCD_E = 0;
delay(5);
}
void lcd_write_data(unsigned char dat) //写数据
{
LCD_RS = 1;
LCD_RW = 0;
LCD_DAT = dat;
delay(5);
LCD_E = 1;
delay(5);
LCD_E = 0;
delay(5);
}
void lcd_init() //LCD初始化
{
lcd_write_cmd(0x38);
lcd_write_cmd(0x08);
lcd_write_cmd(0x01);
lcd_write_cmd(0x06);
lcd_write_cmd(0x0c);
}
void lcd_show_string(unsigned char x, unsigned char y, unsigned char *str) //在指定位置显示字符串
{
unsigned char i;
if (x < 16)
{
if (y == 0)
lcd_write_cmd(0x80 + x);
else
lcd_write_cmd(0x80 + 0x40 + x);
}
i = 0;
while (str[i] != '\0')
{
lcd_write_data(str[i]);
i++;
}
}
void ds18b20_init() //DS18B20温度传感器初始化
{
unsigned char i;
LCD_DAT = 0;
delay(200);
LCD_DAT = 1;
delay(20);
i = LCD_DAT;
delay(200);
}
void ds18b20_write(unsigned char dat) //写一个字节
{
unsigned char i;
for (i = 0; i < 8; i++)
{
LCD_DAT = 0;
delay(5);
LCD_DAT = dat & 0x01;
delay(5);
LCD_DAT = 1;
dat >>= 1;
}
}
unsigned char ds18b20_read() //读一个字节
{
unsigned char i, dat = 0;
for (i = 0; i < 8; i++)
{
LCD_DAT = 0;
delay(5);
LCD_DAT = 1;
delay(5);
dat >>= 1;
if (LCD_DAT)
dat |= 0x80;
}
return dat;
}
void ds18b20_convert() //启动温度转换
{
ds18b20_init();
ds18b20_write(0xcc);
ds18b20_write(0x44);
}
void main()
{
unsigned char str[16];
float temp;
lcd_init();
while (1)
{
ds18b20_convert();
ds18b20_init();
ds18b20_write(0xcc);
ds18b20_write(0xbe);
temp = ds18b20_read() / 2.0;
sprintf(str, "TEMP:%.1f", temp);
lcd_show_string(0, 0, str);
delay(500);
}
}
```
这个代码使用了DS18B20温度传感器来获取温度值,并将其显示在LCD1602上。你可以根据自己的需要修改代码。注意,在使用这个代码之前,你需要了解51单片机的基本编程知识。
阅读全文