最近在做一个arduino nano 驱动DS18B20,不用oneWire和DallasTemperature的库文件,但结果总是不对,显示4096℃。
时序参考了很多资料和项目,是没问题的,但在Arduino上就不对了。请高手指点一下!上代码:
int DSPIN=9;
void setup()
{
Serial.begin(9600);
}
void loop()
{
float tem=0;
tem = TempRead();
tem=tem*0.0625;//转换精度为0.0625/LSB
Serial.println(tem);
delay(1000);
}
void DS18B20_Init()
{
boolean ack=1;
pinMode(DSPIN, OUTPUT);
digitalWrite(DSPIN, HIGH);
delayMicroseconds(2);
while(ack)
{
digitalWrite(DSPIN, LOW);
delayMicroseconds(750);//480-960
digitalWrite(DSPIN, HIGH);
delayMicroseconds(70);
pinMode(DSPIN, INPUT);
if(digitalRead(DSPIN)==1)
ack=1;
else
ack=0;
delayMicroseconds(500);
pinMode(DSPIN, OUTPUT);
delayMicroseconds(2);
}
}
void DS18B20_Write(unsigned char data)
{
unsigned char i,a1;
pinMode(DSPIN, OUTPUT);
digitalWrite(DSPIN, HIGH);
delayMicroseconds(2);
for(i=8;i>0;i–)
{
a1=data&0x01;
digitalWrite(DSPIN, LOW);
delayMicroseconds(15);
if(a1==1)
digitalWrite(DSPIN, HIGH);
delayMicroseconds(45);
digitalWrite(DSPIN, HIGH);
delayMicroseconds(2);
data>>=1;
}
}
unsigned char DS18B20_Read()
{
unsigned char i;
unsigned char data = 0;
for(i=8;i>0;i–)
{
data=data>>1;
pinMode(DSPIN, OUTPUT);
digitalWrite(DSPIN, HIGH);
delayMicroseconds(2);
digitalWrite(DSPIN, LOW);
delayMicroseconds(6);
digitalWrite(DSPIN, HIGH);
delayMicroseconds(4);
pinMode(DSPIN, INPUT);
if(digitalRead(DSPIN)==1)
data=data|0x80;
delayMicroseconds(30);
}
return data;
}
unsigned int TempRead()
{
unsigned int tt=0;
unsigned int a=0;
unsigned int b=0;
unsigned char L=0;
unsigned char H=0;
DS18B20_Init();
DS18B20_Write(0xCC);//发跳过ROM命令
DS18B20_Write(0x44);//发读开始转换命令
delayMicroseconds(1000000);延时1000ms
DS18B20_Init();
DS18B20_Write(0xCC);//发跳过ROM命令
DS18B20_Write(0xBE);//读寄存器,前两字节为转换值
L=DS18B20_Read();//低字节
H=DS18B20_Read();//高字节
a=H;
b=L;
a=(a<<8);
tt=a|b;
return tt;
}