Thursday, 4 April 2019

Finally got 2x NodeMcu temp sensor working

Fixed my NodeMcu Wifi not connecting error:

> w([==[tmr.alarm(1, 2500, 1, configWifi)]==]);
> file.close();
> dofile("init.lua");
NodeMcu temperature monitor v0.3 02-Apr-19
> Configuring WIFI..
nil
Configuring WIFI..
nil
Configuring WIFI..
nil
Configuring WIFI..

By using the following code:
https://www.limpkin.fr/index.php?post/2016/04/17/A-Small-Collection-of-NodeMCU-Lua-Scripts-for-Data-Collection

function GetSensorData()
    -- print( "Trying to get temperature..." )
    pin = 4
    error = 0 
    status, temp, humi, temp_dec, humi_dec = dht.read(pin)
    if status == dht.OK then
        --print("DHT Temperature:"..temp..";".."Humidity:"..humi)
        error = 0
    elseif status == dht.ERROR_CHECKSUM then
        -- print( "DHT Checksum error." )
        error = 1
    elseif status == dht.ERROR_TIMEOUT then
        -- print( "DHT timed out." )
        error = 2
    end
    return error, temp, humi 
end

function configWifi()
      print("Configuring WIFI..")
      print(wifi.sta.getip()) 
      wifi.setmode(wifi.STATION)
      station_cfg={} 
      station_cfg.ssid=SSID
      -- station_cfg.ssid="Wifi-Repeater(2.4G)"
      station_cfg.pwd=PASSWORD
      station_cfg.save=true
      wifi.sta.config(station_cfg)
      wifi.sta.connect()
      tmr.alarm(1, 1000, 1, function()
          if wifi.sta.getip() == nil then
              print("IP unavaiable, Waiting...")
          else
              tmr.stop(1)
              print("ESP8266 mode is: " .. wifi.getmode())
              print("The module MAC address is: " .. wifi.ap.getmac())
              print("Config done, IP is "..wifi.sta.getip())
              makeConn() -- can now startt publishing results
          end
      end)
end





sensorID = "NodeMcu_" .. node.chipid()   -- a sensor identifier for this device
tgtHost = "192.168.1.136"    -- target host (broker)
tgtPort = 1883          -- target port (broker listening on)
mqttTimeOut = 120        -- connection timeout
mqttUserID = USERNAME        -- account to use to log into the broker
mqttPass = PASSWORD     -- broker account password
dataInt = 5           -- data transmission interval in seconds
tempQueue  = "/temperatures/" .. sensorID     -- the MQTT topic queue to use
humidQueue = "/humidities/" .. sensorID   -- the MQTT topic queue to use
connected = 0 -- not connected to MQTT broker
  
-- Function pubEvent() publishes the sensor value to the defined queue.

function pubEvent() 
    err, t, humid = GetSensorData() -- read temp
    if (err == 0) then

      print("Publishing to " .. tempQueue .. ": " .. t)   -- print a status message
      mqttBroker:publish(tempQueue, t, 0, 0)  -- publish

      print("Publishing to " .. humidQueue .. ": " .. humid)   -- print a status message
      mqttBroker:publish(humidQueue, humid, 0, 0)  -- publish
    end
end




-- Reconnect to MQTT when we receive an "offline" message.

function reconn()
    connected = 0
    print("Disconnected, reconnecting....")
    conn()
end



-- Establish a connection to the MQTT broker with the configured parameters.

function conn()
    connected = 0
    print("Making connection to MQTT broker")
    mqttBroker:connect(tgtHost, tgtPort, 0, function(client) print ("connected") end, function(client, reason) print("failed reason: "..reason) end)
end



-- Call this first! --
-- makeConn() instantiates the MQTT control object, sets up callbacks,
-- connects to the broker, and then uses the timer to send sensor data.
-- This is the "main" function in this library. This should be called 
-- from init.lua (which runs on the ESP8266 at boot), but only after
-- it's been vigorously debugged. 
--
-- Note: once you call this from init.lua the only way to change the
-- program on your ESP8266 will be to reflash the NodeCMU firmware! 

function makeConn() 
    -- Instantiate a global MQTT client object
    print("Instantiating mqttBroker")
    mqttBroker = mqtt.Client(sensorID, mqttTimeOut, mqttUserID, mqttPass, 1)

    -- Set up the event callbacks
    print("Setting up callbacks")
    mqttBroker:on("connect", 
      function(client) 
        print ("connected") 
        connected = 1
      end)
    mqttBroker:on("offline", reconn)

    -- Connect to the Broker
    conn()

    -- Use the watchdog to call our sensor publication routine
    -- every dataInt seconds to send the sensor data to the 
    -- appropriate topic in MQTT.
    tmr.alarm(0, (dataInt * 1000), 1, pubEvent)
end

-- MAIN
print( "NodeMcu temperature monitor v0.3 02-Apr-19" )
configWifi()

Now still get the odd PANIC but the unit reboots and recovers. Here's its output:


NodeMCU custom build by frightanic.com
branch: master
commit: 11592951b90707cdcb6d751876170bf4da82850d
SSL: false
modules: dht,ds18b20,file,gpio,mqtt,net,node,tmr,uart,wifi
 build created on 2019-03-31 09:31
 powered by Lua 5.1.4 on SDK 2.2.1(6ab97e9)
NodeMcu temperature monitor v0.3 02-Apr-19
Configuring WIFI..
nil
> IP unavaiable, Waiting...
IP unavaiable, Waiting...
IP unavaiable, Waiting...
ESP8266 mode is: 1
The module MAC address is: ee:fa:bc:28:71:df
Config done, IP is 192.168.1.146
Instantiating mqttBroker
Setting up callbacks
Making connection to MQTT broker
connected
Publishing to /temperatures/NodeMcu_2650591: 20
Publishing to /humidities/NodeMcu_2650591: 35
Publishing to /temperatures/NodeMcu_2650591: 20
Publishing to /humidities/NodeMcu_2650591: 36
Publishing to /temperatures/NodeMcu_2650591: 20

Happy days! So now flashing another 3 NodeMcus :)

However, the MQTT temp and humidity values being published aren't being retained.


Also want to wire on a DHT22 rather than a DHT11

DHT22 Tutorial for Raspberry Pi | Rototron

and grab a couple of decimal points of precision on the readings. Also need to fix the MQTT retention issue and add the voltage to the ADC (so we can know when the batter is going flat! :) )

So here's Mark 2 up and running with Mark 1 :)


Finally, thought I'd monitor theses two sensors using Node-Red and found the PCB mounted one is much hotter!

I blew on the white DHT22 to get 100% humidity and to raise the temp.
Then held the blue DHT11 one for a while.




No comments:

Post a Comment