void delay(unsigned int x) //5us
{
while(x)
{
x--;
}
}
void port_init(void) //端口定义
{
PORTB = 0x03;
DDRB = 0x17;
}
void init_1820(void)
{
DS18B20_SET;
DS18B20_CRL;
// delay(1000); //480us以上
delay(200);
DS18B20_SET;
DDRB&=~(1<<PB4);
delay(10); //15~60us
while(PINB&(1<<PB4))
{
;
}
DDRB|=(1<<PB4);
DS18B20_SET;
delay(15); //60~240us
}
void write_1820(unsigned char x)
{
unsigned char m;
for(m=0;m<8;m++)
{
DS18B20_CRL;
if(x&(1<<m)) //写数据,从低位开始
DS18B20_SET;
else
DS18B20_CRL;
delay(4); //15~60us
DS18B20_SET;
}
DS18B20_SET;
}
unsigned char read_1820(void)
{
unsigned char temp,k,n;
temp=0;
for(n=0;n<8;n++)
{
DS18B20_CRL;
// delay(2);
DS18B20_SET;
//delay(3);
DDRB&=~(1<<PB4);
k=(PINB&(1<<PB4)); //读数据,从低位开始
if(k)
temp|=(1<<n);
else
temp&=~(1<<n);
delay(3); //60~120us
DDRB|=(1<<PB4);
}
return (temp);
}
signed int readTempDS18B20()
{
unsigned char temh=0,teml=0,zorf=0;
unsigned int val=0;
init_1820(); //复位18b20
write_1820(0xcc); // 发出转换命令
write_1820(0x44);
delay(8);
init_1820();
write_1820(0xcc); //发出读命令
write_1820(0xbe);
teml=read_1820(); //读数据
temh=read_1820();
zorf=(temh>>3)&0x1F;
if(zorf)
{
teml^=0xff;
temh^=0xff;
teml += 1;
val=(temh<<8)|teml;
val>>=4;// val/=16;
temp_ok = 0-val;
}
else
{
val=(temh<<8)|teml;
val>>=4;// val/=16;
temp_ok = val;
}
return temp_ok;
}
程序我发上来 ,大家 帮我看看啊
|