EDIT: Thanks el_supremo and jimmus!! Questions updated with answers.
Hey all, I'm currently playing with some DS18B20P temperature sensors and the OneWire library and the DS18x20 example and am confused with how the temperature is retrieved. According to the datasheet, the data is stored in the scratch pad in an LS byte and a MS byte.
First question, what is LS/MS? Answer: Least Significant / Most Significant
Next, one wire displays the retrieved data as 28 01 4B 46 1F FF 08 10 DC.
Second question: why do we need to retrieve so many bytes if the temp is only two bytes? Answer: We don't need to, but it may be faster to retrieve the other bytes than to cancel it.
Next, in the code, the temperature is extracted from the first and second byte and stored in a int16_t. The second byte is used as the more important bit, so it is fed to the int16_t (raw) as 01 28, which in decimal is 296. Next, the code gets what is refereed to as cfg from the data and then does a bitwise and with 0x60.
Third question: why does it modify the configuration data with 0x60? Answer: This removes other information and only retains the two bits which control resolution.
Next, based on the cfg value, it has a few options. For whatever reason I don't know yet, the execution branch I'm seeing is cfg == 0x00, so then the code has raw = raw & ~7.
Fourth question: what is raw = raw & ~7? I've found info on bitwise & and bitwise ~, but not both. Answer: 7 is binary 111, ~7 is 1111111111111000, which masks off the lower three bits not in use for 9 bit resolution.
Finally, the result is divided by 16. In the datasheet it indicates the value is stored as a two-compliments value, so I'm guessing the division has something to do with that, but the examples I've found for twos-compliment doesn't divide by 16, it uses bitwise to flip the digits and add or subtract 1.
Fifth question: why is the result divided by 16? Answer: Highest resolution is 1/16th of a degree Celsius, decimals take more bits to store, so actual temp is stored as temp multiplied by 16. Have to reverse the multiplication to get the decimals back.