Post your best Lua script examples here

User avatar
By Sbiriguda
#30586 Hi guys, I need your help because i'm getting crazy with reading the temperature using the ds18b20 and sending data to thingspeak.
My problem is that, when I read the temperature I'm unable to send the data to thingspeak but if I comment all the part that reads the data from the sensor and insert a fake temperature data, the connection with thingspeak went good.
I've tried different codes with different types of boards (ESP-01 and ESP-12) but the problem remain the same. Now, i'm using the following configuration

ds18b20 connected as shown here http://mo.mosfet.co/2015/03/08/ESP8266-temperature-sensor.html
Code: Select allConnect the pull-up resistor between VCC and DQ (middle pin) on the DS18B20
Connect pin 1 (GND) and pin 3 (Vdd) on the DS18B20 to common ground.
Connect DQ to GPIO2 on the ESP
Connect TX/RX to your 3.3V serial cable


and using the following code:

Code: Select allfunction sendData(temp)
     t1 = temp / 10000
     t2 = (temp >= 0 and temp % 10000) or (10000 - temp % 10000)
     print("Temp:"..t1 .. "."..string.format("%04d", t2).." C\n")
     -- conection to thingspeak.com
     print("Sending data to thingspeak.com")
     conn=net.createConnection(net.TCP, 0)
     conn:on("receive", function(conn, payload)
                                   print(payload)
                                   conn:close()
                                   end)
     -- api.thingspeak.com 184.106.153.149
     conn:connect(80,'184.106.153.149')
     str = "GET /update?key=<key>&field1="..t1.."."..string.format("%04d", t2).." HTTP/1.1\r\nHost: api.thingspeak.com\r\n".."Connection: close\r\nAccept: */*\r\n\r\n"
     conn:send(str)
end

function work()
     sendData(31000)
end

function work1()
     t = require("ds18b20")
     
     gpio2 = 4
     
     t.setup(gpio2)
     addrs = t.addrs()
     if (addrs ~= nil) then
       print("Total DS18B20 sensors: "..table.getn(addrs))
     end
     
     -- Just read temperature
     temp = t.read()
     print("Temperature: "..t.read().."°C")
     
     -- Don't forget to release it after use
     t = nil
     ds18b20 = nil
     package.loaded["ds18b20"]=nil

     sendData(temp)
end


wifi.setmode(wifi.STATION)

print("******* 5 seconds delay *******");
tmr.alarm(2,5000,0, function()
     wifi.sta.config("SSID","password")
     wifi.sta.connect()
     print("DHCP delay (5 s.)...");
     tmr.delay(5000000)
     work1()
     tmr.alarm(0, 30000, 1, function() work1() end )
end)


If I use the "work" function all works perfect, but if I use the "work1" function the connection does not complete and the data is not saved.

Please, help me :)

Thanks