实验电路图
实验代码
main.c
#include <reg52.h>
#include <ds18b20.h>
#include <LCD.h>
uint count_temp=0;
uint temp=0;
uchar table[]={0,0};
uchar table1[]={0,0};
uchar temper[]="temperature:";
void System_Init();
void Time0Init();
void Lcd_Display();
void main()
{
System_Init();
while(1)
{
Lcd_Display();
if(count_temp>749)
{
count_temp=0;
temp=(float)ReadTemperature()*0.0625*100+0.5;
}
}
}
void Time0Init()
{
TMOD=0X01;
TL0 = 0x18;
TH0 = 0xFC;
TF0 = 0;
TR0 = 1;
ET0=1;
EA=1;
}
void Time0() interrupt 1
{
TL0 = 0x18;
TH0 = 0xFC;
count_temp++;
}
void System_Init()
{
int i;
for(i=0;i<79;i++)
temp=(float)ReadTemperature()*0.0625*100+0.5;
Time0Init();
init();
}
void Lcd_Display()
{
uint i;
table[0]=temp/1000;
table[1]=temp%1000/100;
table1[0]=temp%1000%100/10;
table1[1]=temp%10;
write_com(0x80);
for(i=0;i<12;i++)
{
write_data(temper[i]);
delay(5);
}
write_com(0x80+0x40);
write_data(table[0]+48);
write_data(table[1]+48);
delay(5);
write_com(0x80+0x42);
write_data('.');
write_data(table1[0]+48);
write_data(table1[1]+48);
delay(5);
}
LCD.h
#ifndef __LCD_H__
#define __LCD_H__
#include<reg52.h>
#include<intrins.h>
#include<ds18b20.h>
void write_com(uchar com);
void write_data(uchar dat);
void init();
sbit RS=P3^1;
sbit E=P3^2;
#endif
LCD.c
#include<LCD.h>
void write_com(uchar com){
E=0;
RS=0;
P0=com;
delay(5);
E=1;
delay(5);
E=0;
}
void write_data(uchar dat){
E=0;
RS=1;
P0=dat;
delay(5);
E=1;
delay(5);
E=0;
}
void init(){
write_com(0x38);
write_com(0x0c);
write_com(0x06);
write_com(0x01);
}
ds18b20.h
#ifndef __DS18B20_H__
#define __DS18B20_H__
#include<reg52.h>
#include<intrins.h>
#define uchar unsigned char
#define uint unsigned int
sbit DQ=P1^4;
unsigned int ReadTemperature(void);
bit Init_DS18B20(void);
unsigned char ReadOneChar(void);
void WriteOneChar(unsigned char dat);
void delay(ms);
#endif
#include"ds18b20.h"
void DelayUs2x(unsigned char t)
{
uchar i;
for(i=0;i<t;i++)
{
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
_nop_();
}
}
bit Init_DS18B20(void)
{
bit dat=0;
DQ = 1;
DelayUs2x(1);
DQ = 0;
DelayUs2x(20);
DelayUs2x(20);
DQ = 1;
DelayUs2x(5);
dat=DQ;
DelayUs2x(3);
return dat;
}
unsigned char ReadOneChar(void)
{
unsigned char i=0;
unsigned char dat = 0;
for (i=8;i>0;i--)
{
DQ = 0;
dat>>=1;
DQ = 1;
if(DQ)
dat|=0x80;
DelayUs2x(3);
}
return(dat);
}
void WriteOneChar(unsigned char dat)
{
unsigned char i=0;
for (i=8; i>0; i--)
{
DQ = 0;
DQ = dat&0x01;
DelayUs2x(3);
DQ = 1;
dat>>=1;
}
DelayUs2x(3);
}
unsigned int ReadTemperature(void)
{
unsigned char a=0;
unsigned int b=0;
unsigned int t=0;
Init_DS18B20();
WriteOneChar(0xCC);
WriteOneChar(0x44);
delay(10);
Init_DS18B20();
WriteOneChar(0xCC);
WriteOneChar(0xBE);
a=ReadOneChar();
b=ReadOneChar();
b<<=8;
t=a+b;
return(t);
}
void delay(ms){
uint i,j;
for(i=0;i<ms;i++){
for(j=0;j<123;j++){
}
}
}
|