本帖最后由 qaz411140525 于 2013-8-22 12:55 编辑
////////////这是51单片机学习板上写的程序///////////////////
#include <reg52.h>
#include <intrins.h>
#define uint unsigned int
#define uchar unsigned char
sbit dula=P2^6;
sbit wela=P2^7;
sbit DQ=P2^2; //温度数据
uint temp;
float ftemp; float tt;
uchar timecount;
uchar tflag,sflag;
unsigned char code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,
0x07,0x7f,0x6f,0xbf,0x86,0xdb,0xcf,0xe6,0xed,0xfd,0x87,0xff,0xef,};
void delay(uint x)
{
while(x--);
}
/*
delay(1) 延时 7us
delay(7) 延时63us
delay(100) 延时 611us
*/
void delay1(uint x)
{
uint i,j;
for(i=x;i>0;i--)
for(j=110;j>0;j--);
}
void init_18b20()
{
uint i;
i=3000;
DQ = 1;
delay(1);
DQ = 0;
delay(100);
DQ=1;
while(DQ==0&&i>0) i--;
delay(80);
DQ=1;
}
//读字节
uchar readonebyte( )
{
bit flag = 0;
uchar i = 0, temp2 = 0;
for(i = 0; i < 8; i++)
{
temp2=temp2>>1;
DQ=1;
_nop_();
DQ = 0;
delay(1);
DQ = 1;
delay(1);
flag = DQ;
if(flag == 1)
temp2= temp2|0x80;
delay(7);
DQ = 1;
_nop_();
_nop_();
}
return temp2;
}
//写字节
void writeonebyte(uchar date)
{
uchar temp1= 0, i = 0;
temp1= date;
for(i = 0; i < 8; i++)
{
DQ = 0
delay(2);
DQ = temp1 & 0x01;
delay(7);
DQ = 1;
temp1= temp1>>1;
}
}
void readtemp()
{
uchar a=0,b=0;
init_18b20();
writeonebyte(0xcc);
writeonebyte(0x44);
delay1(1000);
init_18b20();
writeonebyte(0xcc);
writeonebyte(0xbe);
a=readonebyte();
delay1(5);
b=readonebyte();
temp=b;
temp<<=8;
temp=temp|a;
tt=temp*0.0625;
temp=tt*10+0.5;
}
void display(uint temp) //显示程序
{
dula=1;
P0=table[temp/1000];
dula=0;
P0=0xff;
wela=1;
P0=0xfe;
wela=0;
delay(5);
dula=1;
P0=table[temp%100/10+10];
dula=0;
P0=0xff;
wela=1;
P0=0xfd;
wela=0;
delay(5);
dula=1;
P0=table[temp%100%10];
dula=0;
P0=0xff;
wela=1;
P0=0xfb;
wela=0;
delay(5);
}
void main()
{
while(1)
{
readtemp();
display(temp);
}
}
|