onewire-ds18b20.lua 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. --'
  2. -- ds18b20 one wire example for NODEMCU (Integer firmware only)
  3. -- NODEMCU TEAM
  4. -- LICENCE: http://opensource.org/licenses/MIT
  5. -- Vowstar <vowstar@nodemcu.com>
  6. --'
  7. pin = 9
  8. ow.setup(pin)
  9. count = 0
  10. repeat
  11. count = count + 1
  12. addr = ow.reset_search(pin)
  13. addr = ow.search(pin)
  14. tmr.wdclr()
  15. until((addr ~= nil) or (count > 100))
  16. if (addr == nil) then
  17. print("No more addresses.")
  18. else
  19. print(addr:byte(1,8))
  20. crc = ow.crc8(string.sub(addr,1,7))
  21. if (crc == addr:byte(8)) then
  22. if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then
  23. print("Device is a DS18S20 family device.")
  24. repeat
  25. ow.reset(pin)
  26. ow.select(pin, addr)
  27. ow.write(pin, 0x44, 1)
  28. tmr.delay(1000000)
  29. present = ow.reset(pin)
  30. ow.select(pin, addr)
  31. ow.write(pin,0xBE,1)
  32. print("P="..present)
  33. data = nil
  34. data = string.char(ow.read(pin))
  35. for i = 1, 8 do
  36. data = data .. string.char(ow.read(pin))
  37. end
  38. print(data:byte(1,9))
  39. crc = ow.crc8(string.sub(data,1,8))
  40. print("CRC="..crc)
  41. if (crc == data:byte(9)) then
  42. t = (data:byte(1) + data:byte(2) * 256)
  43. -- handle negative temperatures
  44. if (t > 0x7fff) then
  45. t = t - 0x10000
  46. end
  47. if (addr:byte(1) == 0x28) then
  48. t = t * 625 -- DS18B20, 4 fractional bits
  49. else
  50. t = t * 5000 -- DS18S20, 1 fractional bit
  51. end
  52. local sign = ""
  53. if (t < 0) then
  54. sign = "-"
  55. t = -1 * t
  56. end
  57. -- Separate integral and decimal portions, for integer firmware only
  58. local t1 = string.format("%d", t / 10000)
  59. local t2 = string.format("%04u", t % 10000)
  60. local temp = sign .. t1 .. "." .. t2
  61. print("Temperature= " .. temp .. " Celsius")
  62. end
  63. tmr.wdclr()
  64. until false
  65. else
  66. print("Device family is not recognized.")
  67. end
  68. else
  69. print("CRC is not valid!")
  70. end
  71. end