Post your best Lua script examples here

User avatar
By mfkfx1
#39727 Hello,

when I put the example DHT22 code in a file, lets say in "mqtt.lua" and call it from somewhere else with dofile("mqtt.lua"), the variable mqtt_state is always zero.
It seems that the lifetime of the variable ends when exiting the file. When the file is called again, it is created again and initialized with zero.
Am I right about this? How can I solve it (e.g. making it "static" like in C).

Regards
User avatar
By goingmad
#40268 Hello,

first of all thanks to all the contributors to this (and the others) topic, it 's of great help for newcomers to this exciting IoT world.

As said, I'm new and before asking for help usually browse a lot searching for answers, so here I am with my problems:

- I have a MQTT / Node Red server working in an Ubuntu VM
- I have flashed my ESP8266 (wemos mini D1 and NodeMCU) with different versions of firmware to find an exit to the bottleneck (using the Windows ESP8266 flasher). Currently NodeMCU 0.9.6 build 20150704 floating on it.
- I have adapted to my setup the init.lua and transferred it, together with dht22.lua through Esplorer (also compiled dht22.lua) as found in post #1
- I have a DHT22 connected to the ESP8266 in a breadboard

My ESP connects to the MQTT server and nothing more, errors shown as follows:

NodeMCU 0.9.6 build 20150704 powered by Lua 5.1.4
> Connected to MQTT:192.168.1.140:1883 as ESP1
PANIC: unprotected error in call to Lua API (init.lua:44: attempt to perform arithmetic on global 'humid' (a nil value))
PANIC: unprotected error in call to Lua API (attempt to perform arithmetic on a nil value)
PANIC: unprotected error in call to Lua API (attempt to concatenate a nil value)
PANIC: unprotected error in call to Lua API (attempt to concatenate a nil value)
PANIC: unprotected error in call to Lua API (attempt to concatenate a nil value)
PANIC: unprotected error in call to Lua API (attempt to concatenate a nil value)
PANIC: unprotected error in call to Lua API (attempt to concatenate a nil value)
PANIC: unprotected error in call to Lua API (attempt to call a string value)
��!�)�f�&!�F� ʰ���

My codes:

init.lua

Code: Select all-- Engineered by MikeV, modded by rutierut

t=require("dht22")

broker = "192.168.1.140"     -- 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
mqtt_state = 0           -- State control


wifi.setmode(wifi.STATION)
wifi.sta.config("myssi","mypw")
wifi.sta.connect()


function dhtsensor()
dht22 = require("dht22")
dht22.read(GPIO2)
temp = dht22.getTemperature()
humid = dht22.getHumidity()
end

function mqtt_do()
     count = count + 1  -- For testing number of interations before failure
     
     if mqtt_state < 5 then
          mqtt_state = wifi.sta.status() --State: Waiting for wifi

     elseif mqtt_state == 5 then
     m = mqtt.Client(clientID, 120, userID, userPWD)
          m:connect( broker , mqttport, 0,
          function(conn)
               print("Connected to MQTT:" .. broker .. ":" .. mqttport .." as " .. clientID )
               mqtt_state = 20 -- Go to publish state             
          end)

     elseif mqtt_state == 20 then
          mqtt_state = 25 -- Publishing...
          dhtsensor() -- Getting values
          m:publish("Testtopic","Temperature: "..((temp-(temp % 10)) / 10).."."..(temp % 10).." C, Humidity: "..(humid / 10).."."..(humid % 10).."%", 0, 0,
          function(conn)
              -- Print confirmation of data published
              print(" Sent messeage #"..count.."\nTemp:"..((temp-(temp % 10)) / 10).."."..(temp % 10).."\nHumidity: "..(humid/10).."."..(humid % 10).."\npublished!")
              mqtt_state = 20  -- Finished publishing - go back to publish state.
          end)
     else print("Publishing..."..mqtt_state)
          mqtt_state = mqtt_state - 1  -- takes us gradually back to publish state to retry
     end

end

-- release module
dht22 = nil
package.loaded["dht22"] = nil

tmr.alarm(0, 10000, 1, function() mqtt_do() end) -- convert 10000 to dynamic variable


the dht22.lua is the untouched ver. by Javier Yanez, as found in post #1.

I'm stuck with the errors loop, cannot find a solution for that.

Any hints?

thanks, regards

gm
User avatar
By AdamJWood
#50213 It seems MQTT has changed a bit over the past year. I couldn't get prior examples to work perfectly so I spent several hours poking at the code until I settled on something decent. Hopefully this will help another noob like myself. Sorry, almost no comments explaining the code but it's very barebones so I trust it isn't that much of an inconvenience.

Purpose: Publish temperature and humidity once per minute

Software/Firmware:
Mosquitto for Windows v1.4.9 (default settings - no username/password)
NodeMCU custom build by frightanic.com
type: float
branch: dev or master
modules: dht,file,gpio,mqtt,net,node,tmr,uart,wifi
powered by Lua 5.1.4 on SDK 1.5.1 (e67da894)

Hardware:
NodeMCU development board
DHT22 Temperature/Humidity Sensor

Code: Select allfunction temperature()
pin = 5
status, temp, humi = dht.read(pin)
tempF = (1.8 * temp + 32)
tmr.alarm(1, 100, tmr.ALARM_SINGLE, function() connectMQTT() end)
end

function connectMQTT()
m = mqtt.Client("esp8266-sensor1", 120)
m:connect("192.168.0.102", 1883, 0)
m:on("connect", function(client) print("connected") pubMQTT() end)
end

function pubMQTT()
m:publish("Home/Data/Sensor1", "Temp: "..tempF.." ; ".."Humidity: "..humi, 2, 0, function(client) print("publishing") end)
end

-- publish every X ms (once/minute)
tmr.alarm(0, 60000, 1, function() temperature() end)
User avatar
By Siddhartha
#53418 Hi,
Great post.
This is a request for guidance.
My ESP8266 module connects to “test.mosquitto.org” and subscribes to a topic say “b1”. What ever is published to “b1”, it can read it immediately.
Problem happens when my second ESP8266 module subscribes to “test.mosquitto.org” to “b1”. It continuously returns :

WiFi connected
IP address:
192.168.0.9
Attempting MQTT connection…connected
Message arrived [b1] 0
Attempting MQTT connection…connected
Message arrived [b1] 0
Attempting MQTT connection…connected
Message arrived [b1] 0
Attempting MQTT connection…connected

Could you kindly suggest what might be going wrong. I look forward to your advice.