DS18B20温控系统
- 格式:doc
- 大小:1.21 MB
- 文档页数:8
DS18B20实时温度显示
数码管采用了共阴极数码管,由于所选用的单片机输出电流小,所以采用了三极管驱动,三极管用的是s9013,为了提高亮度,还选择了74HC138译码器作为数码管的选择,74HC138的灌电流能及较强。
一、效果图
二、详细源代码
#include<reg52.h>
#define uchar unsigned char
#define uint unsigned int
sbit DS = P2 ^ 2; //ds18b20的数据线引脚
uint temp; //临时存放温度数据
//接74HC138的ABC引脚
sbit wdzs = P2 ^ 7;//选中整数十位
sbit wdzg = P2 ^ 6;//选中整数个位
sbit wdxs = P2 ^ 5;//选中小数十位
sbit wdxg = P2 ^ 4;//选中小数个位
uchar A1, A2, A2t, A3, A3t, A4;
unsigned char code table[] = {//不带小数点的段码0x3F, 0x06, 0x5B, 0x4F, 0x66,
0x6D, 0x7D, 0x07, 0x7F, 0x6F };
unsigned char code tabledot[] = {//带小数点的段码 (电路连接:PX.7)
0xBF, 0x86, 0xDB, 0xCF, 0xE6,
0xED, 0xFD, 0x87, 0xFF, 0xEF };
//延时函数
void delay(uint count)
{
uint i;
while (count)
{
i = 200;
while (i>0)
i--;
count--;
}
}
//发送重置和初始化命令
void dsreset(void)
{
uint i;
DS = 0;
i = 103;
while (i>0)i--;
DS = 1;
i = 4;
while (i>0)i--;
}
//读取一个位的数
bit tmpreadbit(void)
{
uint i;
bit dat;
DS = 0; i++; //i++ 用于延时几个时钟周期i
DS = 1; i++; i++;
dat = DS;
i = 8; while (i>0)i--;
return (dat);
}
//读取一个字节的数据
uchar tmpread(void)
{
uchar i, j, dat;
dat = 0;
for (i = 1; i <= 8; i++)
{
j = tmpreadbit();
dat = (j << 7) | (dat >> 1); //读出的数据最低位在最前面,这样刚好一个字节在DAT里
}
return(dat);
}
//写一个字节的数据到ds18b20中
void tmpwritebyte(uchar dat)
{
uint i;
uchar j;
bit testb;
for (j = 1; j <= 8; j++)
{
testb = dat & 0x01;
dat = dat >> 1;
if (testb) //写入 1
{
DS = 0;
i++; i++;
DS = 1;
i = 8; while (i>0)i--;
}
else
{
DS = 0; //写入 0
i = 8; while (i>0)i--;
DS = 1;
i++; i++;
}
}
}
void tmpchange(void)
{
dsreset();
delay(1);
tmpwritebyte(0xcc);
tmpwritebyte(0x44);
}
//获取温度
uint tmp()
{
float tt;
uchar a, b;
dsreset();
delay(1);
tmpwritebyte(0xcc);//发跳过ROM命令
tmpwritebyte(0xbe);//发开始转换命令
a = tmpread();
b = tmpread();
temp = b;
temp <<= 8; //两个字节组合为1个字temp = temp | a;
tt = temp*0.0625;
temp = tt * 10 + 0.5;
return temp;
}
void display(uint temp) //显示程序{
A1 = temp / 100;
A2t = temp % 100;
A2 = A2t / 10;
A3 = A2t % 10;
wdzs = 0;
wdzg = 0;
wdxs = 0;
P1 = table[A1];//显示整数十位
delay(2);
wdzs = 1;
wdzg = 0;
wdxs = 0;
P1 = tabledot[A2]; //显示整数个位
delay(2);
wdzs = 0;
wdzg = 1;
wdxs = 0;
P1 = table[A3]; //显示小数十位}
void main()
{
do
{
tmpchange();
display(tmp());
} while (1);
}
三、DS18B20引脚图。