Post your best Lua script examples here

User avatar
By foxt
#33019 Final update: I have the fpmdht code running with the testdht script, and the temps and humidity are reporting correctly. After inspecting the difference between testdht.lua and dht.lua, I have to agree with others who posted that the difference in results is tied to the different sampling rates between testdht.lua and dht.lua.

Since I am more interested in learning about ESP8266 vs DHT22 sample rates, I'll stop here, with thanks to the contributors to this thread!
User avatar
By Przemm
#34520
foxt wrote:I have a devkip 0.9, running nodemcu 0.9.6 20150704 build (floating point version), and can't get the sensor to report correctly. There is a consistent checksum error when testing with wots.lua:

dofile("wots.lua")
checksum 183
checksumTest 192
humidity - timing of bits 0 1 1 1 5 4 5 1 1 1 1 1 1 1 1 1
temperat - timing of bits 1 1 1 1 1 5 5 1 4 2 5 1 4 5 1 1
checksum - timing of bits 5 1 4 5 1 10 10 10
Humidity: 0%
Temperature: 170.8 deg C

When I run fpmdht.lua (with sensor type correctly set to dht22), I get the following error:

dofile("fpmdht.lua")
fpmdht.lua:37: attempt to call field 'getHumidity' (a nil value)

I do have dht.lua installed.

Any suggestions for either problem?



Hello,
Check this lua scripts, i made some corrections and it works with DHT22 and nodemcu_integer_0.9.6-dev_20150704 firmware.

fpmdht.lua
Code: Select all--    Demo http server for sensors DHT11/22
--    Tested with Lua NodeMCU 0.9.5 build 20150127 floating point !!!
-- 1. Flash Lua NodeMCU to ESP module.
-- 2. Set in program fpmdht.lua sensor type. This is parameter typeSensor="dht11" or "dht22".
-- 3. You can rename the program fpmdht.lua to init.lua
-- 4. Load program fpmdht.lua and dht.lua to ESP8266 with LuaLoader
-- 5. HW reset module
-- 6. Login module to your AP - wifi.setmode(wifi.STATION),wifi.sta.config("yourSSID","yourPASSWORD")
-- 7. Run program fpmdht.lua - dofile(fpmdht.lua)
-- 8. Test IP address - wifi.sta.getip()
-- 9. Test it with your browser and true IP address of module.
--10. The sensor is repeatedly read every minute.
--11. The pictures on page are external.
--12. The length of html code is limited to 1460 characters including header.
--    The author of the program module dht.lua for reading DHT sensor is Javier Yanez
               --*******************************
sensorType="dht22"    -- set sensor type dht11 or dht22
               --*******************************

   wifi.setmode(wifi.STATION)
   wifi.sta.config("xxx","xxx")
   wifi.sta.connect()
   tmr.delay(1000000)
   humi="XX"
   temp="XX"
   fare="XX"
   count=1
   PIN = 1 --  data pin, GPIO2
--load DHT module and read sensor
function ReadDHT()
   dht=require("testdht")
   dht.read(PIN)
   if sensorType=="dht11"then
   humi=dht.getHumidity()/256
   temp=dht.getTemperature()/256
   else
   humi=dht.getHumidity()/10
   temp=dht.getTemperature()/10
   end
   fare=(temp*9/5+32)
   print("Humidity:    "..humi.."%")
   print("Temperature: "..temp.." deg C")
   print("Temperature: "..fare.." deg F")
   -- release module
   dht=nil
   package.loaded["dht"]=nil
end

ReadDHT()
tmr.alarm(1,60000,1,function()ReadDHT()count=count+1 if count==5 then count=0 wifi.sta.connect()print("Reconnect")end end)

srv=net.createServer(net.TCP) srv:listen(80,function(conn)
    conn:on("receive",function(conn,payload)
   --print(payload) -- for debugging only
   strstr={string.find(payload,"GET / HTTP/1.1")}
   if(strstr[1]~=nil)then
   --generates HTML web site
   conn:send('HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nCache-Control: private, no-store\r\n\r\n\
   <!DOCTYPE HTML>\
    <html><head><meta content="text/html;charset=utf-8"><title>ESP8266</title></head>\
   <body bgcolor="#ffe4c4"><h2>Hygrometer with<br>'..sensorType..' sensor</h2>\
   <h3><font color="green">\
   <IMG SRC="http://esp8266.fancon.cz/common/hyg.gif"WIDTH="64"HEIGHT="64"><br>\
   <input style="text-align: center"type="text"size=4 name="j"value="'..humi..'"> % of relative humidity<br><br>\
   <IMG SRC="http://esp8266.fancon.cz/common/tmp.gif"WIDTH="64"HEIGHT="64"><br>\
   <input style="text-align: center"type="text"size=4 name="p"value="'..temp..'"> Temperature grade C<br>\
   <input style="text-align: center"type="text"size=4 name="p"value="'..fare..'"> Temperature grade F</font></h3>\
   <IMG SRC="http://esp8266.fancon.cz/common/'..sensorType..'.gif"WIDTH="200"HEIGHT="230"BORDER="2"></body></html>') end
    conn:on("sent",function(conn) conn:close() end)
    end)
end)





testdht.lua :
Code: Select all-- ***************************************************************************
-- for communication of DHT sensor only
-- DHT module for ESP8266 with nodeMCU floating point
-- Written by Javier Yanez
-- but based on a script of Pigs Fly from ESP8266.com forum
-- MIT license, http://opensource.org/licenses/MIT
-- ***************************************************************************

local moduleName = ...
local M = {}
_G[moduleName] = M

local humidity
local temperature

function M.read(pin)
  local checksum
  local checksumTest
  humidity = 0
  temperature = 0
  checksum = 0

  -- Use Markus Gritsch trick to speed up read/write on GPIO
  local gpio_read = gpio.read

  local bitStream = {}
   for j = 1, 40, 1 do
    bitStream[j] = 0
  end
  local bitlength = 0

  -- Step 1:  send out start signal to DHT22
  gpio.mode(pin, gpio.OUTPUT)
  gpio.write(pin, gpio.HIGH)
  tmr.delay(100)
  gpio.write(pin, gpio.LOW)
  tmr.delay(20000)
  gpio.write(pin, gpio.LOW)
  gpio.mode(pin, gpio.INPUT)

  -- Step 2:  DHT22 send response signal
  -- bus will always let up eventually, don't bother with timeout
  while (gpio_read(pin) == 0 ) do end
  local c=0
  while (gpio_read(pin) == 1 and c < 500) do c = c + 1 end
  -- bus will always let up eventually, don't bother with timeout
  while (gpio_read(pin) == 0 ) do end
  c=0
  while (gpio_read(pin) == 1 and c < 500) do c = c + 1 end

  -- Step 3: DHT22 send data
  for j = 1, 40, 1 do
    while (gpio_read(pin) == 1 and bitlength < 20 ) do
      bitlength = bitlength + 1
    end
    bitStream[j] = bitlength
    bitlength = 0
    -- bus will always let up eventually, don't bother with timeout
    while (gpio_read(pin) == 0) do end
  end
   hum=" "
   tem=" "
   chk=" "
  --DHT data acquired, process.
  for i = 1, 16, 1 do
  hum=hum.." "..tostring(bitStream[i])
  tem=tem.." "..tostring(bitStream[i+16])
   if (bitStream[i] > 3) then
      humidity = humidity + 2 ^ (16 - i)
   end
    if (bitStream[i + 16] > 3) then
      temperature = temperature + 2 ^ (16 - i)
   end
  end
  for i = 1, 8, 1 do
  chk=chk.." "..tostring(bitStream[i+32])
   if (bitStream[i + 32] > 3) then
      checksum = checksum + 2 ^ (8 - i)
   end
  end
    checksumTest = (bit.band(humidity, 0xFF) + bit.rshift(humidity, 8) + bit.band(temperature, 0xFF) + bit.rshift(temperature, 8))
  checksumTest = bit.band(checksumTest, 0xFF)

  if temperature > 0x8000 then
    -- convert to negative format
    temperature = -(temperature - 0x8000)
  end

  -- conditions compatible con float point and integer
  if (checksumTest - checksum >= 1) or (checksum - checksumTest >= 1) then
   humidity = -1
   print("checksum ERROR")
  end
end

function M.getTemperature()
  return temperature
end

function M.getHumidity()
  return humidity
end

return M

User avatar
By ogsmokie
#37282 Hello , the ESP8266 with NodeMCU supports DHT11 sensors others I have not yet tested .

That is also the reason why the file ' dht.lua ' causes an error . NodeMCU uses himself the name DHT for specific libraries , which are the same specific libraries for DHT sensors in the Arduino IDE .

Under https://github.com/nodemcu/nodemcu-firmwarecan be found at the very bottom of this page to Universal Sensor DHT support . This works really easily :

Code: Select allpin = 5
status,temp,humi,temp_decimial,humi_decimial = dht.readxx(pin)
if( status == dht.OK ) then
  -- Integer firmware using this example
  print(
    string.format(
      "DHT Temperature:%d.%03d;Humidity:%d.%03d\r\n",
      math.floor(temp),
      temp_decimial,
      math.floor(humi),
      humi_decimial
    )
  )
  -- Float firmware using this example
  print("DHT Temperature:"..temp..";".."Humidity:"..humi)
elseif( status == dht.ERROR_CHECKSUM ) then
  print( "DHT Checksum error." );
elseif( status == dht.ERROR_TIMEOUT ) then
  print( "DHT Time out." );
end
User avatar
By PascalS
#53427 Hy jankop,

jankop wrote:Previous program does not work correctly in floating point. That's why I edited it for floating point arithmetic. For proper operation, it is necessary to set in program fpmdht.lua sensor type. This is parameter typeSensor = "dht11" or "dht22".

Load program fpmdht.lua and dht.lua to ESP8266 with LuaLoader


Code: Select all--    Demo http server for sensors DHT11/22
--    Tested with Lua NodeMCU 0.9.5 build 20150127 floating point !!!
-- 1. Flash Lua NodeMCU to ESP module.
-- 2. Set in program fpmdht.lua sensor type. This is parameter typeSensor="dht11" or "dht22".
-- 3. You can rename the program fpmdht.lua to init.lua
-- 4. Load program fpmdht.lua and dht.lua to ESP8266 with LuaLoader
-- 5. HW reset module
-- 6. Login module to your AP - wifi.setmode(wifi.STATION),wifi.sta.config("yourSSID","yourPASSWORD")
-- 7. Run program fpmdht.lua - dofile(fpmdht.lua)
-- 8. Test IP address - wifi.sta.getip()
-- 9. Test it with your browser and true IP address of module.
--10. The sensor is repeatedly read every minute.
--11. The pictures on page are external.
--12. The length of html code is limited to 1460 characters including header.
--    The author of the program module dht.lua for reading DHT sensor is Javier Yanez
               --*******************************
sensorType="dht22"    -- set sensor type dht11 or dht22
               --*******************************

   wifi.setmode(wifi.STATION)
   --wifi.sta.config("yourSSID","yourPASSWORD")
   wifi.sta.connect()
   tmr.delay(1000000)
   humi="XX"
   temp="XX"
   fare="XX"
   count=1
   PIN = 4 --  data pin, GPIO2
--load DHT module and read sensor
function ReadDHT()
   dht=require("dht")
   dht.read(PIN)
   if sensorType=="dht11"then
   humi=dht.getHumidity()/256
   temp=dht.getTemperature()/256
   else
   humi=dht.getHumidity()/10
   temp=dht.getTemperature()/10
   end
   fare=(temp*9/5+32)
   print("Humidity:    "..humi.."%")
   print("Temperature: "..temp.." deg C")
   print("Temperature: "..fare.." deg F")
   -- release module
   dht=nil
   package.loaded["dht"]=nil
end

ReadDHT()
tmr.alarm(1,60000,1,function()ReadDHT()count=count+1 if count==5 then count=0 wifi.sta.connect()print("Reconnect")end end)

srv=net.createServer(net.TCP) srv:listen(80,function(conn)
    conn:on("receive",function(conn,payload)
   --print(payload) -- for debugging only
   strstr={string.find(payload,"GET / HTTP/1.1")}
   if(strstr[1]~=nil)then
   --generates HTML web site
   conn:send('HTTP/1.1 200 OK\r\nConnection: keep-alive\r\nCache-Control: private, no-store\r\n\r\n\
   <!DOCTYPE HTML>\
    <html><head><meta content="text/html;charset=utf-8"><title>ESP8266</title></head>\
   <body bgcolor="#ffe4c4"><h2>Hygrometer with<br>'..sensorType..' sensor</h2>\
   <h3><font color="green">\
   <IMG SRC="http://esp8266.fancon.cz/common/hyg.gif"WIDTH="64"HEIGHT="64"><br>\
   <input style="text-align: center"type="text"size=4 name="j"value="'..humi..'"> % of relative humidity<br><br>\
   <IMG SRC="http://esp8266.fancon.cz/common/tmp.gif"WIDTH="64"HEIGHT="64"><br>\
   <input style="text-align: center"type="text"size=4 name="p"value="'..temp..'"> Temperature grade C<br>\
   <input style="text-align: center"type="text"size=4 name="p"value="'..fare..'"> Temperature grade F</font></h3>\
   <IMG SRC="http://esp8266.fancon.cz/common/'..sensorType..'.gif"WIDTH="200"HEIGHT="230"BORDER="2"></body></html>') end
    conn:on("sent",function(conn) conn:close() end)
    end)
end)


Thank you for his Code! Thats really geat! :)

I have a question, How can I insert an HTTP-GET request in this code, whose result looks like "http://example.com/upload.php?tempf=69.98$tempc=21.1$humidity=67"?

I have already tried many ways but unfortunately nothing works ...

Thank you for your help!


Best regards,
PascalS