這是溫度程序,正常運行沒問題,但是插進別的程序就會閃爍而且不穩定。
#include"temp.h"
void Delay1ms(uint y)
{
uint x;
for( ; y>0; y--)
{
for(x=110; x>0; x--);
}
}
uchar Ds18b20Init()
{
uchar i;
DSPORT = 0; //將總線拉低480us~960us
i = 70;
while(i--);//延時642us
DSPORT = 1; //然后拉高總線,如果DS18B20做出反應會將在15us~60us后總線拉低
i = 0;
while(DSPORT) //等待DS18B20拉低總線
{
Delay1ms(1);
i++;
if(i>5)//等待>5MS
{
return 0;//初始化失敗
}
}
return 1;//初始化成功
}
void Ds18b20WriteByte(uchar dat)
{
uint i, j;
for(j=0; j<8; j++)
{
DSPORT = 0;
i++;
DSPORT = dat & 0x01;
i=6;
while(i--);
DSPORT = 1;
dat >>= 1;
}
}
uchar Ds18b20ReadByte()
{
uchar byte, bi;
uint i, j;
for(j=0;j<8;j++)
{
DSPORT = 0;
i++;
DSPORT = 1;
i++;
i++;
bi = DSPORT;
byte = (byte >> 1) | (bi << 7);
i = 4;
while(i--);
}
return byte;
}
void Ds18b20ChangTemp()
{
Ds18b20Init();
Delay1ms(1);
Ds18b20WriteByte(0xcc); //跳過ROM操作命令
Ds18b20WriteByte(0x44); //溫度轉換命令
}
void Ds18b20ReadTempCom()
{
Ds18b20Init();
Delay1ms(1);
Ds18b20WriteByte(0xcc);
Ds18b20WriteByte(0xbe);
}
int Ds18b20ReadTemp()
{
int temp = 0;
uchar tmh, tml;
Ds18b20ChangTemp(); //先寫入轉換命令
Ds18b20ReadTempCom(); //然后等待轉換完后發送讀取溫度命令
tml = Ds18b20ReadByte(); //讀取溫度值共16位,先讀低字節
tmh = Ds18b20ReadByte(); //再讀高字節
temp = tmh;
temp <<= 8;
temp |= tml;
return temp;
}
|