通过DS18B20测量外界温度并显示在数码管上,温度值需精确到小数点后2位
main.c
#include"STC15F2K60S2.h"
#include"onewire.h"
#include"intrins.h"
typedef unsigned char uchar;
typedef unsigned int uint;
uchar dsp_code[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
uchar dsp_Temp[8]={0xff,0xff,0xff,0xff};
uint temp;
uchar count_temp;
void Timer_Init()
{
AUXR|= 0x80;
TMOD&= 0xf0;
TL0=0xcd;
TH0=0xd4;
TR0=1;
ET0=1;
EA=1;
}
void serviceTimer() interrupt 1
{
static uchar dsp_com=0;
P0=0;P2=0xc0;P2=0;
P0=dsp_Temp[dsp_com];P2=0xe0;P2=0;
P0=1<759)
{
count_temp=0;
temp=read_temp()*100+0.5;
}
dsp_Temp[4]=dsp_code[temp/1000];
dsp_Temp[5]=dsp_code[temp/100%10]&0x7f;
dsp_Temp[6]=dsp_code[temp/10%10];
dsp_Temp[7]=dsp_code[temp%10];
}
}
onewire.c
#include "reg52.h"
#include"onewire.h"
#include"intrins.h"
sbit DQ = P1^4; //单总线接口
//单总线延时函数
void Delay_oneWire(unsigned int t); //STC89C52RC
//通过单总线向DS18B20写一个字节
void Write_DS18B20(unsigned char dat)
{
unsigned char i;
for(i=0;i<8;i++)
{
DQ = 0;
DQ = dat&0x01;
Delay_oneWire(5);
DQ = 1;
dat >>= 1;
}
Delay_oneWire(5);
}
//从DS18B20读取一个字节
unsigned char Read_DS18B20(void)
{
unsigned char i;
unsigned char dat;
for(i=0;i<8;i++)
{
DQ = 0;
dat >>= 1;
DQ = 1;
if(DQ)
{
dat |= 0x80;
}
Delay_oneWire(5);
}
return dat;
}
//DS18B20设备初始化
bit init_ds18b20(void)
{
bit initflag = 0;
DQ = 1;
Delay_oneWire(12);
DQ = 0;
Delay_oneWire(80);
DQ = 1;
Delay_oneWire(10);
initflag = DQ;
Delay_oneWire(5);
return initflag;
}
void Delay_onewire(unsigned int t)
{
t*=11;
while(t--);
}
float read_temp()
{
float temp;
unsigned char low,high;
init_ds18b20();
Write_DS18B20(0xcc);
Write_DS18B20(0x44);
Delay_oneWire(200);
init_ds18b20();
Write_DS18B20(0xcc);
Write_DS18B20(0xbe);
low=Read_DS18B20();
high=Read_DS18B20();
temp=(high<<8|low)*0.0625;
return temp;
}
onewire.h
#ifndef __ONEWIRE_H #define __ONEWIRE_H float read_temp(); bit init_ds18b20(void); unsigned char Read_DS18B20(void); void Delay_oneWire(unsigned int t); void Write_DS18B20(unsigned char dat); unsigned char rd_temperature(void); //; ; #endif



