Search code examples
luaesp8266nodemcu

Reading DHT22 sensor with NodeMCU


I'm trying to read temperature data from a DHT22 using NodeMCU. This is my script:

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
end

-- MAIN
tmr.alarm(1, 1000, 1, function() GetSensorData() end)

This gives me the following output (over and over):

Trying to get temperature... DHT timed out. ....

I tried every possible value for "pin", and attached the DHT22 data output to all GPIOs of my NodeMCU.

The pins are connected like this:

  • DHT22-VCC -> NodeMCU-3.3V
  • DHT22-GND -> NodeMCU-GND
  • DHT22-DATA -> NodeMCU-D0, D1, D2, D3, D4 (tried em all)

I've run out oif ideas. What could be the problem here?


Solution

  • Ok, here we go...

    Pin numbers must be mapped from what it says on the module to an index that you use in Lua code. See https://nodemcu.readthedocs.org/en/dev/en/modules/gpio. For example with pin = 4 you'd have to use GPIO2 on the module.