Post your best Lua script examples here

User avatar
By chadouming
#12429
rutierut wrote:Added support for humidity & removed a useless part of example 1


I've modified your code for more consistency and fixed a few typos.

Here is the MQTT temperature and humidity :

Code: Select all-- Engineered by MikeV, modded by rutierut
broker = "10.0.1.32"    -- IP or hostname of MQTT broker
mqttPort = 1883         -- MQTT port (default 1883)
userID = ""             -- username for authentication if required
userPWD  = ""           -- user password if needed for security
clientID = "ESP1"       -- Device ID
GPIO2 = 4               -- IO Index of GPIO2 which is connected to an LED
count = 0              -- Test number of mqtt_do cycles
mqttState = 0          -- State control

-- Wifi credentials
SSID = ""
wifiPWD = ""

function wifi_connect()
   wifi.setmode(wifi.STATION)
   wifi.sta.config(SSID,wifiPWD)
   wifi.sta.connect()
end

function read_dht()
   dht22 = require("dht22")
   dht22.read(GPIO2)

   if dht22 == nil then
     print("Error reading from DHT22")
     temp = -256 --Prevent division by zero or nil error, while being out of real possible values.
     humidity = -256
   else
      temp = round(dht22.getTemperature()/10, 2)
      humidity = round(dht22.getHumidity()/10, 2)
   end
   dht22 = nil
   package.loaded["dht22"]=nil
end

function mqtt_do()
     count = count + 1  -- For testing number of interations before failure
     
     if mqttState < 5 then
          mqttState = wifi.sta.status() --State: Waiting for wifi
        wifi_connect()
     elseif mqttState == 5 then
     m = mqtt.Client(clientID, 120, userID, userPWD)
          m:connect( broker , mqttport, 0,
          function(conn)
               print("Connected to MQTT:" .. broker .. ":" .. mqttport .." as " .. clientID )
               mqttState = 20 -- Go to publish state             
          end)

     elseif mqttState == 20 then
          mqttState = 25 -- Publishing...
          read_dht() -- Getting values
          m:publish("Testtopic","Temperature: "..temp.." C, Humidity: "..humidity.."%", 0, 0,
          function(conn)
              -- Print confirmation of data published
              print(" Sent messeage  #:"..count.."Temp:"..temp.."Humidity: "..humidity.."% published!")
              mqttState = 20  -- Finished publishing - go back to publish state.
          end)
     else print("Publishing..."..mqttState)
          mqttState = mqttState - 1  -- takes us gradually back to publish state to retry
     end

end

function round(val, decimal) -- Avoid temperature like 21.000000001243
  if (decimal) then
    return math.floor( (val * 10^decimal) + 0.5) / (10^decimal)
  else
    return math.floor(val+0.5)
  end
end

tmr.alarm(0, 10000, 1, function() mqtt_do() end)


And the MQTT button

Code: Select all-- Engineered by rutierut, inspired by MikeV
broker = "10.0.1.32"     -- IP or hostname of MQTT broker
mqttPort = 1883          -- MQTT port (default 1883)
userID = ""              -- username for authentication if required
userPWD  = ""            -- user password if needed for security
clientID = "ESP1"        -- Device ID
GPIO2 = 4                -- IO Index of GPIO2 which is connected to an LED
ready = 0
previousButtonPress = 0
gpio.mode(GPIO2, gpio.INPUT)

-- Wifi credentials
SSID = ""
wifiPWD = ""

function wifi_connect()
   wifi.setmode(wifi.STATION)
   wifi.sta.config(SSID,wifiPWD)
   wifi.sta.connect()
   ip = wifi.sta.getip()
   if ip ~= nil then
      print('Connected, ip is:' .. ip)
      tmr.stop(1)
      ready = 1
   else
      ready = 0
   end
end

function mqtt_do()
if ready == 1 then
  m = mqtt.Client(clientID, 120, userID, userPWD)
  m:connect( broker , mqttport, 0,
  function(conn)
    print("Connected to MQTT:" .. broker .. ":" .. mqttPort .." as " .. clientID )
    tmr.stop(0)
    connected = 1;
  end)
end
end

function button_pressed()
  currentime = tmr.now()
  delta = currentime - previousButtonPress
  previousbuttonpress = tmr.now()
  if delta >= 200000 then
  print('Button pressed')
  publishing = 1;
  m:publish("Frontdoor","Button Pressed", 0, 0,
    function(conn)
      -- Print confirmation of data published
      print(" Message published!")
      publishing = 0;
      -- Finished publishing - go back to publish state.
    end)
    elseif delta <= 200000 then
    print('Delta was too small')
    else
    print('error')
    end
end
     
gpio.trig(GPIO2, "down", button_pressed)
   
tmr.alarm(0, 1000, 1, function()
     mqtt_do()
     tmr.delay(1000)
     end)
     
tmr.alarm(1, 1111, 1, function()
     wifi_connect()
     end)


Use them as you want.
User avatar
By fluppie007
#12507 I get the following error when pressing the button on D4 / GPIO2

> §„Fêh!9ÿ@h…ÿòÇ!9Œ¦¨Hø
NodeMCU 0.9.5 build 20150311 powered by Lua 5.1.4
> Button pressed
PANIC: unprotected error in call to Lua API (init.lua:49: attempt to index global 'm' (a nil value))
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to ind?2ˆÈ©™Ž@H6ÎôŒÕÊüŒ¦¨Hø
NodeMCU 0.9.5 build 20150311 powered by Lua 5.1.4
>
Hard Restart maandag 23 maart 2015 21:56:57
User avatar
By chadouming
#12519
fluppie007 wrote:I get the following error when pressing the button on D4 / GPIO2

> §„Fêh!9ÿ@h…ÿòÇ!9Œ¦¨Hø
NodeMCU 0.9.5 build 20150311 powered by Lua 5.1.4
> Button pressed
PANIC: unprotected error in call to Lua API (init.lua:49: attempt to index global 'm' (a nil value))
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to index a nil value)
PANIC: unprotected error in call to Lua API (attempt to ind?2ˆÈ©™Ž@H6ÎôŒÕÊüŒ¦¨Hø
NodeMCU 0.9.5 build 20150311 powered by Lua 5.1.4
>
Hard Restart maandag 23 maart 2015 21:56:57


Can you try with this code please :

Code: Select all-- Engineered by rutierut, inspired by MikeV
broker = "10.0.1.32"     -- IP or hostname of MQTT broker
mqttPort = 1883          -- MQTT port (default 1883)
userID = ""              -- username for authentication if required
userPWD  = ""            -- user password if needed for security
clientID = "ESP1"        -- Device ID
GPIO2 = 4                -- IO Index of GPIO2 which is connected to an LED
ready = 0
previousButtonPress = 0
gpio.mode(GPIO2, gpio.INPUT)

-- Wifi credentials
SSID = ""
wifiPWD = ""

function wifi_connect()
   wifi.setmode(wifi.STATION)
   wifi.sta.config(SSID,wifiPWD)
   wifi.sta.connect()
   tmr.alarm(1, 1000, 1, function() 
     if wifi.sta.getip() ~= nil then
          tmr.stop(1)
        mqtt_do()
          button_pressed()
     end
     end)
end

function mqtt_do()
if ready == 1 then
  m = mqtt.Client(clientID, 120, userID, userPWD)
  m:connect( broker , mqttport, 0,
  function(conn)
    print("Connected to MQTT:" .. broker .. ":" .. mqttPort .." as " .. clientID )
    tmr.stop(0)
    connected = 1;
  end)
end
end

function button_pressed()
  currentime = tmr.now()
  delta = currentime - previousButtonPress
  previousbuttonpress = tmr.now()
  if delta >= 200000 and connected == 1 then
  print('Button pressed')
  publishing = 1;
  m:publish("Frontdoor","Button Pressed", 0, 0,
    function(conn)
      -- Print confirmation of data published
      print(" Message published!")
     wifi.sta.disconnect()
     connected = 0;
      publishing = 0;
      -- Finished publishing - go back to publish state.
    end)
    elseif delta <= 200000 then
    print('Delta was too small')
    else
    print('error')
    end
end
     
gpio.trig(GPIO2, "down", wifi_connect())