Tuesday, 2 April 2019

Got NodeMcu and DHT11 to work..

Spent the day on my monthly accounts and only just getting back to NodeMcu work :)

So used NodeMCU PyFlasher to burn new image to flash (see earlier posts for details) and then ran C:\Users\kilnageer\Documents\CoderDojo\2018 Reboot\CH Project\NodeMcu\ESPlorer\ESPlorer.jar to develop the application code :) (also covered earlier)

So I now need an lua app which will:
1) read a room temperature from a DHT22 sensor over a NodeMcu digital input
2) and then publish it to a remote MQTT broker over the local wifi.

So 1) achieved using code at:
https://stackoverflow.com/questions/35383183/reading-dht22-sensor-with-nodemcu


and pin-out from:
http://www.uugear.com/portfolio/dht11-humidity-temperature-sensor-module/
https://www.tdegypt.com/wp-content/uploads/2016/06/esp8266-nodemcu-dev-kit-v3-pins.jpg

which resulted in the following output :) (I can swap DHT11 module for DHT22 sensor later :))


So now on to 2). I will use the code at:
https://www.foobarflies.io/a-simple-connected-object-with-nodemcu-and-mqtt/

Cobbling it all together I used the following code:
(NOTE: real passwords changed to PASSWORD :) )

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

-- MAIN
print( "NodeMcu temperature monitor v0.1 02-Apr-19" )
-- Lets see if we are already connected by getting the IP
ipAddr = wifi.sta.getip()
if ( ( ipAddr == nil ) or  ( ipAddr == "0.0.0.0" ) ) then
  print("Configuring WIFI....")
  wifi.setmode(wifi.STATION)
  station_cfg={}
  station_cfg.ssid="Tola Park"
  station_cfg.pwd="PASSWORD"
  station_cfg.save=true
  wifi.sta.config(station_cfg)
else
  print("Already connect to WIFI....")
end
print(wifi.sta.getip())

sensorID = "temp_001"    -- 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 = "pi"        -- account to use to log into the broker
mqttPass = "PASSWORD"     -- broker account password
dataInt = 5           -- data transmission interval in seconds
topicQueue = "/temps"    -- the MQTT topic queue to use


-- Function pubEvent() publishes the sensor value to the defined queue.

function pubEvent()
    rv = GetSensorData() -- read temp
    pubValue = sensorID .. " " .. rv        -- build buffer
    print("Publishing to " .. topicQueue .. ": " .. pubValue)   -- print a status message
    mqttBroker:publish(topicQueue, pubValue, 0, 0)  -- publish
end




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

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



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

function conn()
    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") 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

print("Starting temp monitor..")
makeConn()

Which gives the 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)
No init.lua yet!
> dofile('test.lua')
NodeMcu temperature monitor v0.1 02-Apr-19
Already connect to WIFI....
192.168.1.145 255.255.255.0 192.168.1.254
Starting temp monitor..
Instantiating mqttBroker
Setting up callbacks
Making connection to MQTT broker
> connected
Trying to get temperature...
DHT Temperature:20;Humidity:21
Publishing to /temps: temp_001 20
Trying to get temperature...
DHT Temperature:20;Humidity:27
Publishing to /temps: temp_001 20
Trying to get temperature...
DHT Temperature:20;Humidity:27
Publishing to /temps: temp_001 20
Trying to get temperature...

And looking at the MQTT.fx output:

So I just need to clean it all up and change file name to init.lua.This means:

1) Replace DHT11 module for a DHT22 sensor - which gives better temperature range and accuracy and uses less power as no red LED always on :)
2) Change the topic to be /sensors/temp/XXXX (where XXXX is the NodeMcu id)
3) Run standalone from a battery and field test it.

NOTE: Code will need to be customised for Kilnageer and re-flashed

Have runtime error running code:

Making connection to MQTT broker
> failed reason: -5
Publishing to /temperatures/NodeMcu_2650591: 27
PANIC: unprotected error in call to Lua API (init.lua:54: not connected)

Did major reworking of code started to look good then wouldn't connect to wifi anymore!

NodeMcu temperature monitor v0.3 02-Apr-19
> Configuring WIFI..
nil
Configuring WIFI..
nil





No comments:

Post a Comment