yet-another-ds18b20.lua 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. ------------------------------------------------------------------------------
  2. -- DS18B20 query module
  3. --
  4. -- LICENCE: http://opensource.org/licenses/MIT
  5. -- Vladimir Dronnikov <dronnikov@gmail.com>
  6. --
  7. -- Example:
  8. -- dofile("ds18b20.lua").read(4, function(r) for k, v in pairs(r) do print(k, v) end end)
  9. ------------------------------------------------------------------------------
  10. local M
  11. do
  12. local bit = bit
  13. local format_addr = function(a)
  14. return ("%02x-%02x%02x%02x%02x%02x%02x"):format(
  15. a:byte(1),
  16. a:byte(7), a:byte(6), a:byte(5),
  17. a:byte(4), a:byte(3), a:byte(2)
  18. )
  19. end
  20. local read = function(pin, cb, delay)
  21. local ow = require("ow")
  22. -- get list of relevant devices
  23. local d = { }
  24. ow.setup(pin)
  25. ow.reset_search(pin)
  26. while true do
  27. tmr.wdclr()
  28. local a = ow.search(pin)
  29. if not a then break end
  30. if ow.crc8(a) == 0 and
  31. (a:byte(1) == 0x10 or a:byte(1) == 0x28)
  32. then
  33. d[#d + 1] = a
  34. end
  35. end
  36. -- conversion command for all
  37. ow.reset(pin)
  38. ow.skip(pin)
  39. ow.write(pin, 0x44, 1)
  40. -- wait a bit
  41. tmr.alarm(0, delay or 100, 0, function()
  42. -- iterate over devices
  43. local r = { }
  44. for i = 1, #d do
  45. tmr.wdclr()
  46. -- read rom command
  47. ow.reset(pin)
  48. ow.select(pin, d[i])
  49. ow.write(pin, 0xBE, 1)
  50. -- read data
  51. local x = ow.read_bytes(pin, 9)
  52. if ow.crc8(x) == 0 then
  53. local t = (x:byte(1) + x:byte(2) * 256)
  54. -- negatives?
  55. if bit.isset(t, 15) then t = 1 - bit.bxor(t, 0xffff) end
  56. -- NB: temperature in Celsius * 10^4
  57. t = t * 625
  58. -- NB: due 850000 means bad pullup. ignore
  59. if t ~= 850000 then
  60. r[format_addr(d[i])] = t
  61. end
  62. d[i] = nil
  63. end
  64. end
  65. cb(r)
  66. end)
  67. end
  68. -- expose
  69. M = {
  70. read = read,
  71. }
  72. end
  73. return M