Browse Source

Add negative temp handling; fix multiplier

Negative temperatures (less than 0°C) are returned as a sign-extended
two's complement number. Subtract 0x10000 to recover the proper
negative value.

Also, do not multiply by 625 twice (thanks to @TerryE).

Signed-off-by: Nick Andrew <nick@nick-andrew.net>
Nick Andrew 8 years ago
parent
commit
99f94acacf
1 changed files with 7 additions and 1 deletions
  1. 7 1
      lua_examples/onewire-ds18b20.lua

+ 7 - 1
lua_examples/onewire-ds18b20.lua

@@ -40,7 +40,13 @@ else
           crc = ow.crc8(string.sub(data,1,8))
           print("CRC="..crc)
           if (crc == data:byte(9)) then
-             t = (data:byte(1) + data:byte(2) * 256) * 625
+             t = (data:byte(1) + data:byte(2) * 256)
+
+             -- handle negative temperatures
+             if (t > 0x7fff) then
+                t = t - 0x10000
+             end
+
              if (addr:byte(1) == 0x28) then
                 t = t * 625  -- DS18B20, 4 fractional bits
              else