📄 18b20.c
字号:
#include <reg51.h>
#define uint unsigned int
#define uchar unsigned char
sbit LCD_EN=P3^4;
sbit LCD_RS=P3^5;
bit flag;
sbit DS18B20_DQ=P2^2;
uchar tab[]={"Temperaturn "};
void delayms(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
delayus(uint z)
{
while(z--);
}
/***************温度18B20***********************************/
//功能:初始化18B20
void DS18B20_init(void)
{
uchar x=0;
DS18B20_DQ = 1; //DS18B20_DQ复位
delayus(8); //稍做延时
DS18B20_DQ = 0; //单片机将DQ拉低
delayus(80); //精确延时 大于 480us
DS18B20_DQ = 1; //拉高总线
delayus(14);
x=DS18B20_DQ; //稍做延时后 如果x=0则初始化成功 x=1则初始化失败
delayus(20);
}
//功能:写18B20一个字节
void DS18B20_write_byte(uchar dat)
{
uchar i=0;
for(i=8; i>0; i--)
{
DS18B20_DQ = 0;
DS18B20_DQ = dat&0x01;
delayus(4);
DS18B20_DQ = 1;
dat>>=1;
}
}
//功能:读18B20读一个字节
uchar DS18B20_read_byte(void)
{
uchar i=0;
uchar dat = 0;
for(i=8;i>0;i--)
{
DS18B20_DQ = 0; // 给脉冲信号
dat>>=1;
DS18B20_DQ = 1; // 给脉冲信号
if(DS18B20_DQ)
dat|=0x80;
delayus(4);
}
return(dat);
}
//功能:读取18B20的温度值
uint DS18B20_read(void)
{
uchar a=0,b=0;
uint t=0;
DS18B20_init();
DS18B20_write_byte(0xcc); // 跳过读序号列号的操作
DS18B20_write_byte(0x44); // 启动温度转换
DS18B20_init();
DS18B20_write_byte(0xcc); //跳过读序号列号的操作
DS18B20_write_byte(0xbe); //读取温度寄存器
a=DS18B20_read_byte(); //读低8位
b=DS18B20_read_byte(); //读高8位
t=b;
if((t&0xf8)==0xf8) //为负
{
flag=1;
b=~b;
a=~a+1;
}
else //为正
flag=0;
b=(b&0x07)<<4;
a=(a&0xf0)>>4;
b=b|a;
return(b);
}
/***************液晶1062**************************************/
void LCD_write_com(uchar com) //写命令
{
P0=com;
LCD_RS=0;
delayms(5);
LCD_EN=1;
delayms(5);
LCD_EN=0;
}
void LCD_write_data(uchar date) //写数据
{
P0=date;
LCD_RS=1;
delayms(5);
LCD_EN=1;
delayms(5);
LCD_EN=0;
}
void LCD_init() //LCD1602初始化
{
uchar i;
LCD_write_com(0x38); //显示16*2接口
LCD_write_com(0x01); //清屏
LCD_write_com(0x0c); //00001DCB,D开显示C显示光标B光标闪烁
LCD_write_com(0x06); //000001NS,N1指针、光标加一,N0指针、光标减一。S1整屏左移N1/右移N0,S0整屏不移动
LCD_write_com(0x80);
for(i=0;i<16;i++)
{
LCD_write_data(tab[i]);
delayms(5);
}
}
void LCD_sfm(uchar date)
{
uchar shi,ge;
shi=date/10;
ge=date%10;
LCD_write_com(0x80+11);
if(flag==1)
LCD_write_data(0x20+13); //“-” 负温度
else
LCD_write_data(0x20); //“空格符” //LCD_write_data(0x20+11)“+” 正温度
LCD_write_data(0x30+shi);
LCD_write_data(0x30+ge);
LCD_write_com(0x80+14); //“。”摄氏度
LCD_write_data(0xd0+14);
LCD_write_com(0x80+15); //“C”
LCD_write_data(0x40+3);
}
/********************主函数********************************************************/
main()
{
DS18B20_init();
LCD_init();
while(1)
{
LCD_sfm(DS18B20_read());
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -