onewire-ds18b20.lua 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. --'
  2. -- 18b20 one wire example for NODEMCU
  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. t1 = t / 10000
  53. t2 = t % 10000
  54. print("Temperature= "..t1.."."..t2.." Centigrade")
  55. end
  56. tmr.wdclr()
  57. until false
  58. else
  59. print("Device family is not recognized.")
  60. end
  61. else
  62. print("CRC is not valid!")
  63. end
  64. end