×
单片机 > 单片机程序设计 > 详情

51单片机基于DS18B20的温度检测并显示在lcd1602上

发布时间:2021-09-27 发布时间:
|

单片机源程序如下:

#include

#include

sbit DQ =P1^3;

sbit RS = P1^5;

sbit RW = P1^6;

sbit EN = P1^7;

void delay(unsigned int i);

void init_DS18B20(void);

unsigned char read_DS18B20(void);

void write_DS18B20(unsigned char dat);

double read_temperature(void);

void init_lcd(void);

void lcd_write_dat(unsigned char dat);

void lcd_write_cmd(unsigned char cmd);

void main(void)

{

double temp;

unsigned char i;

char str[16];

init_lcd();

init_DS18B20();

while(1)

{

temp = read_temperature();

if(temp)

{

sprintf(str,"%f",temp);

for(i=0;i<15;i++)

lcd_write_dat(str[i]);

delay(20000);

init_lcd();

}

}

}


void delay(unsigned int i)

{

while(i--);

}


void init_DS18B20(void)

{

bit flag=1;

while(flag==1)

{

DQ = 1;

DQ = 0;

delay(70);

DQ = 1;

delay(10);

flag=DQ;

delay(20);

}

}


unsigned char read_DS18B20(void)

{

unsigned char i = 0, dat = 0;

for (i=0; i<8; i++)

{

DQ = 0;

dat>>=1;

DQ = 1;

if(DQ)

dat|=0x80;

delay(4);

}

return dat;

}

void write_DS18B20(unsigned char dat)

{

unsigned char i=0;

for (i=0; i<8; i++)

{

DQ = 0;

DQ = dat&0x01;

delay(3);

DQ = 1;

dat>>=1;

}

delay(5);

}


double read_temperature(void)

{

unsigned int temp=0;

double d;

init_DS18B20();

write_DS18B20(0xCC);

write_DS18B20(0x44);

init_DS18B20();

write_DS18B20(0xCC);

write_DS18B0(0xBE);

temp=read_DS18B20();

temp=temp+read_DS18B20()*0x100;

if(temp<0xf000)

{

d=temp*0.0625;

}

else

{

temp=~temp+1;

d=-(temp*0.0625);

}

return d;

}

void init_lcd(void)

{

lcd_write_cmd(0x38);

lcd_write_cmd(0x0f);

lcd_write_cmd(0x06);

lcd_write_cmd(0x01);

delay(100);

}

void lcd_write_dat(unsigned char dat)

{

P2 = dat;

RS = 1;

RW = 0;

EN = 1;

delay(100);

EN = 0;

delay(5000);

}

void lcd_write_cmd(unsigned char cmd)

{

P2 = cmd;

RS = 0;

RW = 0;

EN = 1;

delay(100);

EN = 0;

delay(5000);

}



『本文转载自网络,版权归原作者所有,如有侵权请联系删除』

热门文章 更多
51单片机实现按健连加减程序