#include"reg51.h"
#include"intrins.h"
#define uchar unsigned char
#define uint unsigned int
sbit DSPORT=P3^7;
sbit LSA=P2^2;
sbit LSB=P2^3;
sbit LSC=P2^4;
uchar code smgduan[10]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f};
//uchar DisplayData[8];
void delay(uint z)
{
while(z--);
}
void delayus(uint x,uchar y)
{
uchar i,j;
for(i=x;i>0;i--)
for(j=y;j>0;j--);
}
void Ds18b20Init()
{
uchar st=1;
DSPORT = 1;
_nop_();_nop_();
while(st)
{
DSPORT = 0; //时序很重要,一定要准确;
delayus(149,1); //延时750us
DSPORT = 1;
delayus(4,4); //延时15~60 us;
if(DSPORT == 0) //当 DSPORT=0时,初始化才是正确的;
st = 1;
else st = 0;
delayus(99,1); //延时500us
}
}
void Ds18b20WriteByte(uchar dat) //写是判断数据再写入,
{
uchar i,temp;
DSPORT = 1;
_nop_();_nop_();
for(i=0;i<8;i++)
{
DSPORT = 0;
delayus(0,0); //延时20us
temp=dat&0x01;
// delayus(9,1);
if(temp == 1) //判断,然后把数据置给总线(把数据送走,好判断)
DSPORT = 1;
delayus(2,2); //延时45us
dat>>=1;
DSPORT = 1;
}
}
uchar Ds18b20ReadByte() //读是有了数据再给数据
{
uchar i,dat;
// static bit j;
for(i=0;i<8;i++)
{
dat>>=1;
DSPORT=1;
_nop_();_nop_();
DSPORT=0;
_nop_();_nop_();
_nop_();_nop_();
_nop_();_nop_();
DSPORT=1; //当至高时,传送数据;
_nop_();_nop_();_nop_();_nop_();
// j=DSPORT;
if(DSPORT) //判断总线,高位传送数据;
dat=dat|0x80;
delayus(1,1);
}
return dat;
}
void Ds18b20ChangTemp()
{
Ds18b20Init();
delayus(1,100);
Ds18b20WriteByte(0xcc); //跳过ROM
Ds18b20WriteByte(0x44);
}
void Ds18b20ReadTempCom()
{
Ds18b20Init();
delayus(1,100);
Ds18b20WriteByte(0xcc);
Ds18b20WriteByte(0xbe);
}
int Ds18b20ReadTemp()
{
int temp=0;
uchar tmh,tml;
Ds18b20ChangTemp();
Ds18b20ReadTempCom();
tml=Ds18b20ReadByte();
tmh=Ds18b20ReadByte();
temp=(tmh*256+tml)*0.0625*100+0.5; //乘100使其小数点前两位,加0.5使其四舍五入;
return temp;
}
void display(int temp)
{
uchar i;
/***在此不能这样转换,因为上面的temp已经转换为一个数值,取反出来有错,
这样只是数码管上的数值取反了,而不是DS18B20公式取反! ****/
/* int tp; // float 不能取位;
if(temp<0)
{
DisplayData[0]=0x40; //if小于0,则前面加一个 '-' ;
temp=temp-1;
temp=~temp;
tp=temp;
}
else //大于0,则前面的不显示 ;
{
DisplayData[0]=0x00;
tp=temp;
} */
for(i=0;i<4;i++)
{
switch(i)
{
// case 0: LSA=0;LSB=0;LSC=1; P0=DisplayData[0]; break;
case 0: LSA=1;LSB=1;LSC=0; P0=smgduan[temp/1000]; break;
case 1: LSA=0;LSB=1;LSC=0; P0=smgduan[temp%1000/100]|0x80; break;
case 2: LSA=1;LSB=0;LSC=0; P0=smgduan[temp%100/10]; break;
case 3: LSA=0;LSB=0;LSC=0; P0=smgduan[temp%10]; break;
}
delay(100); //延时必须写在清屏前面,
P0=0x00;
}
}
void main()
{
while(1)
{
display(Ds18b20ReadTemp());
}
}
拿去吧,这个是c51的板子程序,管脚改了,数码管程序按照你的板子写就可以显示了,只能帮你到这里了,别的靠你自己加油。 |