DS18B20温度测量
ds18b20.h
#ifndef __DS18B20_H__
#define __DS18B20_H__
#include <reg52.h>
#ifndef uchar
#define uchar unsigned char
#endif
#ifndef uint
#define uint unsigned int
#endif
sbit DQ = P3^7;
uchar Ds18b20Init();
uchar Ds18b20ReadByte();
void Ds18b20WriteByte(uchar dat);
int Ds18b20ReadTemp();
void Send_str(char *str);
void Delay500us();
#endif
ds18b20.c
#include "DS18B20.H"
#include <intrins.h>
bit fg = 1;
void Delay500us()
{
unsigned char i, j;
i = 6;
j = 93;
do
{
while (--j);
} while (--i);
}
void Delay68us()
{
unsigned char i, j;
_nop_();
_nop_();
i = 1;
j = 183;
do
{
while (--j);
} while (--i);
}
void delay(uint x)
{
while( x -- );
}
void Send_str(char *str)
{
while(*str)
{
SBUF = *str;
str ++;
while(!TI);
TI = 0;
}
}
uchar Ds18b20Init()
{
DQ = 1;
delay(8);
DQ = 0;
Delay500us();
DQ = 1;
Delay68us();
fg = DQ;
Delay500us();
return fg;
}
uchar Ds18b20ReadByte()
{
uchar i, dat = 0;
for( i = 0; i < 8; i ++)
{
DQ = 1;
delay(8);
DQ = 0;
dat >>= 1;
DQ = 1;
delay(2);
if(DQ)
dat |= 0x80;
Delay68us();
}
return dat;
}
void Ds18b20WriteByte(uchar dat)
{
uchar i, j;
for(i = 0; i < 8; i ++)
{
DQ = 0;
j ++;
DQ = dat & 0x01;
Delay68us();
DQ = 1;
dat >>= 1;
}
}
int Ds18b20ReadTemp()
{
uchar tempH = 0, tempL = 0;
int temp = 0;
Ds18b20Init();
Ds18b20WriteByte(0xcc);
Ds18b20WriteByte(0x44);
delay(125);
Ds18b20Init();
Ds18b20WriteByte(0xcc);
Ds18b20WriteByte(0xbe);
tempL = Ds18b20ReadByte();
tempH = Ds18b20ReadByte();
temp = tempH;
temp <<= 8;
temp |= tempL;
return temp;
}
1.c
#include <reg52.h>
#include <stdio.h>
#include "Ds18b20.h"
sfr AUXR = 0x8e;
sfr BRT = 0x9c;
#define F_f 11059200UL
#define Baud_rate 9600UL
uchar code smgduan[17]=
{0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,
0x7f,0x6f};
sbit ASEG = P1^2;
sbit BSEG = P1^3;
sbit CSEG = P1^4;
sbit DSEG = P1^5;
uchar showdata[4] = { 0 };
char s[20] = { 0 };
void UART_Init()
{
PCON &= 0x7F;
SCON = 0x50;
AUXR &= 0xFB;
BRT = 256 - F_f / (12 * Baud_rate * 32);
AUXR |= 0x11;
}
void seg4show(uchar i)
{
switch(i)
{
case 0: ASEG = 0; BSEG = 1; CSEG = 1; DSEG = 1; break;
case 1: ASEG = 1; BSEG = 0; CSEG = 1; DSEG = 1; break;
case 2: ASEG = 1; BSEG = 1; CSEG = 0; DSEG = 1; break;
case 3: ASEG = 1; BSEG = 1; CSEG = 1; DSEG = 0; break;
default: ASEG = 1; BSEG = 1; CSEG = 1; DSEG = 1; break;
}
P0 = showdata[i];
Delay500us();
P0 = 0x00;
}
void dataProcess(int temp)
{
float tp;
if(temp< 0)
{
showdata[0] = 0x40;
temp=temp-1;
temp=~temp;
tp=temp;
sprintf(s, "当前温度为: -%0.1f℃\n", tp * 0.0625);
temp=tp*0.0625*10+0.5;
}
else
{
showdata[0] = 0x00;
tp=temp;
sprintf(s, "当前温度为: %0.1f℃\n", tp * 0.0625);
temp=tp*0.0625*10+0.5;
}
showdata[1] = smgduan[temp / 100];
showdata[2] = smgduan[temp / 10 % 10] | 0x80;
showdata[3] = smgduan[temp % 10];
}
void main()
{
uchar i;
DQ = 1;
UART_Init();
EA = 1;
ES = 1;
while(1)
{
dataProcess(Ds18b20ReadTemp());
for(i = 0; i < 4; i ++)
{
seg4show(i);
}
}
}
void UART1_Routine() interrupt 4
{
uchar buf_str;
if(RI)
{
buf_str = SBUF;
if(buf_str == 0xaa )
Send_str(s);
RI = 0;
}
}