- Tue Dec 30, 2014 7:55 am
#5958
I modified the original "problematic" script in a bit "assynchronous" way and it is working.
Code: Select allpin = 4
ow.setup(pin)
output = nil
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()
sensors={}
temps={}
counter=0
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
sensor = ""
for j = 1,7 do sensor = sensor .. string.format("%02x", addr:byte(j)) end
sensors[counter] = sensor
ow.reset(pin)
ow.select(pin, addr)
ow.write(pin, 0x44, 1)
tmr.delay(1000 * 1000)
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
if(addr:byte(1) == 0x10) then
-- we have DS18S20, the measurement must change
t = t * 8; -- compensating for the 9-bit resolution only
t = t - 2500 + ((10000 * (data:byte(8) - data:byte(7))) / data:byte(8))
end
temps[counter] = t
end
end
end
end
addr = ow.search(pin)
counter = counter + 1
until(addr == nil)
output = ""
for i, sensorID in ipairs(sensors) do
t1 = temps[i] / 10000
t2 = (temps[i] >= 0 and temps[i] % 10000) or (10000 - temps[i] % 10000)
output = output .. wifi.sta.getmac()
output = output .."\t" .. sensorID .. "\t"
output = output .. t1 .. "." .. string.format("%04d", t2) .. "\n"
end
output = output .. "#"
end
function sendData()
if(output ~= nil) then
if(string.byte(output, -1) == string.byte("#")) then
print("About to send:\n" .. output)
sk=net.createConnection(net.TCP, 0)
sk:on("receive", function(sck, c) print(c) end )
sk:connect(8888, "192.168.11.1")
sk:send(output)
sk:on("sent", function(conn) print "Closing connection" conn:close() end)
output = nil
end
end
end
function checkIP()
if wifi.sta.getip() ~= nil then
tmr.stop(0)
tmr.wdclr()
print("Got IP")
print(wifi.sta.getip())
print("Starting Temp measurement")
getTemp()
tmr.alarm(0,5*1000, 1, sendData)
tmr.alarm(1,30*1000, 1, getTemp)
end
end
tmr.alarm(0, 2 * 1000, 1, checkIP)
However, when removing the first alarm and calling sendData() directly after the measurement, the connection does not work.
Any tips, what is wrong?
Perhaps some timer issue?