【求助帖】DS18B20代码问题
2017-03-161.4万
AI 快速预览详细
本文详细解析了DS18B20温度传感器中的getTemp()函数。首先介绍了OneWire库的初始化和设置,然后逐步解释了getTemp()函数中CRC校验、地址验证及温度读取的具体步骤。通过这些步骤,用户可以理解并调试代码,确保传感器正常工作。
|
DS18B20 防水温度传感器套件附带的代码里面getTemp()的函数看不懂啊,有人可以帮忙解释一下吗 #include <OneWire.h> int DS18S20_Pin = 2; //DS18S20 Signal pin on digital 2 //Temperature chip i/o OneWire ds(DS18S20_Pin); // on digital pin 2 void setup(void) { Serial.begin(9600); } void loop(void) { float temperature = getTemp(); Serial.println(temperature); delay(100); //just here to slow down the output so it is easier to read } float getTemp(){ //returns the temperature from one DS18S20 in DEG Celsius byte data[12]; byte addr[8]; if ( !ds.search(addr)) { //no more sensors on chain, reset search ds.reset_search(); return -1000; } if ( OneWire::crc8( addr, 7) != addr[7]) { Serial.println("CRC is not valid!"); return -1000; } if ( addr[0] != 0x10 && addr[0] != 0x28) { Serial.print("Device is not recognized"); return -1000; } ds.reset(); ds.select(addr); ds.write(0x44,1); // start conversion, with parasite power on at the end byte present = ds.reset(); ds.select(addr); ds.write(0xBE); // Read Scratchpad for (int i = 0; i < 9; i++) { // we need 9 bytes data = ds.read(); } ds.reset_search(); byte MSB = data[1]; byte LSB = data[0]; float tempRead = ((MSB << 8) | LSB); //using two's compliment float TemperatureSum = tempRead / 16; return TemperatureSum; } |




在18B20的产品介绍页面有关于它是如何工作的介绍。
感兴趣的话可以看下。
data是数据,addr是他的指令或者寄存器地址
tempRead = ((MSB << 8) | LSB);
MSB<<8,是将MSB换算成二进制数后,向左平移8位,左边移出的被舍弃,右边补零
| LSB是二进制的常用算法。
((MSB << 8) | LSB);整个命令就是读取温度的常用操作。