本帖最后由 lamp波波 于 2016-8-7 13:08 编辑
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit DS=P2^4;
sbit dot=P0^7; //小数点
uint temp; // variable of temperature
uchar flag1; // sign of the result posi
tive or negative
code unsigned char tab[]={0x40, 0x79, 0x24, 0x30,
0x19, 0x12, 0x02, 0x78,
0x00, 0x10};
uint ad=0, ads;//数字信号变量
uchar StrTab[3];
void delay(uint count) //delay
{
uint i;
while(count)
{
i=200;
while(i>0)
i--;
count--;
}
}
void dsreset(void) //send reset and initialization command
{
uint i;
DS=0;
i=103;
while(i>0)i--;
DS=1;
i=4;
while(i>0)i--;
}
bit tmpreadbit(void) //read a bit
{
uint i;
bit dat;
DS=0;i++; //i++ for delay
DS=1;i++;i++;
dat=DS;
i=8;while(i>0)i--;
return (dat);
}
uchar tmpread(void) //read a byte date
{
uchar i,j,dat;
dat=0;
for(i=1;i<=8;i++)
{
j=tmpreadbit();
dat=(j<<7)|(dat>>1); //????????????,?????????DAT?
}
return(dat);
}
void tmpwritebyte(uchar dat) //write a byte to ds18b20
{
uint i;
uchar j;
bit testb;
for(j=1;j<=8;j++)
{
testb=dat&0x01;
dat=dat>>1;
if(testb) //write 1
{
DS=0;
i++;i++;
DS=1;
i=8;while(i>0)i--;
}
else
{
DS=0; //write 0
i=8;while(i>0)i--;
DS=1;
i++;i++;
}
}
}
void tmpchange(void) //DS18B20 begin change
{
dsreset();
delay(1);
tmpwritebyte(0xcc); // address all drivers on bus
tmpwritebyte(0x44); // initiates a single temperature conversion
}
uint tmp() //get the temperature
{
float tt;
uchar a,b;
dsreset();
delay(1);
tmpwritebyte(0xcc);
tmpwritebyte(0xbe);
a=tmpread();
b=tmpread();
temp=b;
temp<<=8; //two byte compose a int variable
temp=temp|a;
tt=temp*0.0625;
temp=tt*10+0.5;
return temp;
}
void display(uint temp)
{
uint i;
ad = temp;
ads=ad/100;
StrTab[2]=tab[ads];
ad=ad%100;
ads=ad/10;
StrTab[1]=tab[ads];
ad=ad%10;
ads=ad;
StrTab[0]=tab[ads];
for(i=0; i<100; i++)
{
P2=0x01;
P0=StrTab[2];
dot=1;
delay(5);
P2=0x00;
P2=0x02;
P0=StrTab[1];
delay(5);
P2=0x00;
P2=0x04;
P0=StrTab[0];
dot=1;
delay(5);
P2=0x00;
}
}
void main()
{
uchar a;
while(1)
{
tmpchange();
for(a=10;a>0;a--)
{
display(tmp());
}
}
}
-
上电之后
-
快要4s的时间才能正常显示温度
一周热门 更多>