最近在学DS18B20,参考了很多资料,仿照写了个用18B20测温,用4个数码管显示的程序,并在万能板上焊接了实际电路(电路板正常,应为芯片写时钟程序后,数码管显示正常)。把测温程序写在单片机里,通电,数码管一直显示“559C",且不随环境温度变化。那位师傅能帮我看看程序啊!谢谢各位了!
#include<reg51.h> //本程序为18B20测试温度,用4个数码管显示温度的2位整数,1位十分位,1个温度单位“C”
#include<intrins.h> //本程序用到实际焊接好的电路上,数码管一直显示“559C”,且不随温度变化而变,不知何故?
#define uchar unsigned char //芯片用的是STC12C5202AD,晶振用11.0592MHZ
#define uint unsigned int
uint k,xs,t; //t为温度的整数部分,k为温度的小数部分
sbit DQ=P3^2; //数据口define interface
sbit wei1=P3^7; //数码管位选,温度十位
sbit wei2=P3^4; //数码管位选,温度个位
sbit wei3=P3^5; //数码管位选,温度小数点后一位
sbit wei4=P3^3; //数码管位选,温度单位“C”的位选
//共阳数码管编码(不含小数点)
uchar code table[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90,0x88,0x83,0xc6,0xa1,0x86,0x8e};
void delay(uint i) //延时
{while(i--);}
void delay_ms(uint z) //1ms延时
{ uint x,y;
for(x=0;x<z;x++)
for(y=0;y<110;y++);
}
void init() //对DS18B20复位函数
{ DQ=1;
delay(8);
DQ=0;
delay(250);
DQ=1;
delay(100);
}
void write_B(uchar f) //写DS18B20
{ uchar i;
for(i=0;i<8;i++)
{ DQ=0;
DQ=f&0x01;
delay(10);
DQ=1;
f>>=1;
delay(1);
}
}
uchar read_B() //读DS18B20
{ uchar i,b;
for(i=0;i<8;i++)
{ DQ=0;
b>>=1;
DQ=1;
delay(1);
if(DQ)
{b=b|0x80;}
delay(10);
}
return(b);
}
void dq1820()
{ uchar c1,c2;
init(); //对18B20复位
write_B(0xcc); //跳过ROM
write_B(0x44); //启动温度转换
init(); //复位
write_B(0xcc); //跳过ROM
write_B(0xbe); //读RAM命令
c1=read_B(); //读温度的低字节
c2=read_B(); //读温度的高字节
xs=c1&0x0f; //低字节的低4位为小数部分
c1=c1>>4; //低字节的高4位和
c2=c2<<4; //高字节的低4位
t=c2|c1; //合起来为温度的整数部分
k=xs*625; //乘以0.0625为温度值,这里扩大10000倍,避免小数运算
}
void display()
{
uchar A1,A2,A3;
A1 = t/10%10; //温度的十位
A2 = t%10; //温度的个位
A3 = k/1000%10; //温度的0.1位
wei1=0;wei2=1;wei3=1;wei4=1; //位选,打开第一个数码管的供电
P1 = table[A1]; //显示温度十位
delay_ms(4);
wei1=1;wei2=0;wei3=1;wei4=1; //位选,打开第二个数码管的供电
P1 = table[A2]; //显示温度个位
delay_ms(4);
wei1=1;wei2=1;wei3=0;wei4=1; //位选,打开第三个数码管的供电
P1 = table[A3]; //显示温度小数位
delay_ms(4);
wei1=1;wei2=1;wei3=1;wei4=0; //位选,打开第四个数码管的供电
P1 =0xc6; //显示温度单位“C”
delay_ms(4);
wei1=1;wei2=1;wei3=1;wei4=1; //关闭所有位选,清屏
}
void main()
{
uchar h;
dq1820();
for(h=0;h<8;h++)
{
display();
}
}