I had to walk to my freezer like 6 times to put and pull the module and rewrite the code.
In the meantime, I identified a bug in the nodeMCU related to Modulo operation upon negative integer (bug is here: http://www.esp8266.com/viewtopic.php?f=18&t=795).
Until the bug is fixed, following code will work OK:
pin = 9
ow.setup(pin)
counter=0
lasttemp=-999
function bxor(a,b)
local r = 0
for i = 0, 31 do
if ( a % 2 + b % 2 == 1 ) then
r = r + 2^i
end
a = a / 2
b = b / 2
end
return r
end
function getTemp()
addr = ow.reset_search(pin)
repeat
tmr.wdclr()
if (addr ~= nil) then
crc = ow.crc8(string.sub(addr,1,7))
if (crc == addr:byte(8)) then
if ((addr:byte(1) == 0x10) or (addr:byte(1) == 0x28)) then
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
tmr.delay(1000000)
present = ow.reset(pin)
ow.select(pin, addr)
ow.write(pin,0xBE, 1)
data = nil
data = string.char(ow.read(pin))
for i = 1, 8 do
data = data .. string.char(ow.read(pin))
end
crc = ow.crc8(string.sub(data,1,8))
if (crc == data:byte(9)) then
t = (data:byte(1) + data:byte(2) * 256)
if (t > 32768) then
t = (bxor(t, 0xffff)) + 1
t = (-1) * t
end
t = t * 625
lasttemp = t
print("Last temp: " .. lasttemp)
end
tmr.wdclr()
end
end
end
addr = ow.search(pin)
until(addr == nil)
end
srv=net.createServer(net.TCP)
srv:listen(8080,function(conn)
getTemp()
t1 = lasttemp / 10000
t2 = (lasttemp >= 0 and lasttemp % 10000) or (10000 - lasttemp % 10000)
conn:send("Temperature: " .. t1 .. "." .. string.format("%04d", t2) .. "\n\n")
conn:on("sent",function(conn) conn:close() end)
end)
Btw, doing XOR on my own - that's what I call challenge
The line with t2 calculation will have to be modified after the fix of the nodeMCU.
The code runs on the device on port 8080, so I can do
nc esp 8080
and it will reply with
Temperature: -9.1875
The esp is the domain name my router assigns to the device's DHCP request...
If is a single sensor DS18B20 on bus, you can replace the getTemp() with this for speed:
function getTemp()
tmr.wdclr()
ow.reset(pin)
ow.skip(pin)
ow.write(pin,0x44,1)
tmr.delay(800000)
ow.reset(pin)
ow.skip(pin)
ow.write(pin,0xBE,1)
data = nil
data = string.char(ow.read(pin))
data = data .. string.char(ow.read(pin))
t = (data:byte(1) + data:byte(2) * 256)
if (t > 32768) then
t = (bxor(t, 0xffff)) + 1
t = (-1) * t
end
t = t * 625
lasttemp = t
print("Last temp: " .. lasttemp)
end
Great example to get DS18B20 temperatures, I am using your modified code which works with negative temperatures, I connected 2 sensors, and it appears to be very robust however, from the browser when I enter http://192.168.0.179:8080/ and I can see in uploader it gets both temperatures (don't understand why it does this twice ? ):
Last temp: 298750
Last temp: 242500
Last temp: 302500
Last temp: 241875
But on the web page I only get 1 temperature which is always the second one like in this case 24.2500, any idea how I can get this code to print out both readings from the 2 sensors on the webpage ?