Data not showing on IoT Cloud - Nano ESP32 / Micropython / DTH22

Hi there, I'm having some issue with my data showing on my Arduino Cloud dashboard, any advice on what may be happening will be highly appreciated. Thanks!

The setup is very simple:

  • Arduino Nano ESP32
  • Micropython V1.22.1
  • DTH22

The setup is working locally since I can read temp and humidity from the DTH22, however I can't make the script send data to the Arduino cloud. The WiFi works and the nano connects to the internet fine, so I don't know what I'm missing in the code:

from machine import Pin
from time import sleep_ms
from arduino_iot_cloud import ArduinoCloudClient
import dht
import network
import logging

from secrets import WIFI_SSID
from secrets import WIFI_PASSWORD
from secrets import DEVICE_ID
from secrets import CLOUD_PASSWORD

#CONNECT TO THE WIFI

def wifi_connect():
    if not WIFI_SSID or not WIFI_PASSWORD:
        raise (Exception("Network is not configured. Set SSID and passwords in secrets.py"))
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)
    while not wlan.isconnected():
        logging.info("Trying to connect. Note this may take a while...")
        time.sleep_ms(500)
    logging.info(f"WiFi Connected {wlan.ifconfig()}")

if __name__ == "__main__":
    # Configure the logger.
    # All message equal or higher to the logger level are printed.
    # To see more debugging messages, set level=logging.DEBUG.
    logging.basicConfig(
        datefmt="%H:%M:%S",
        format="%(asctime)s.%(msecs)03d %(message)s",
        level=logging.INFO,
    )

 # NOTE: Add networking code here or in boot.py
wifi_connect()

# Define sensor pin
SENSOR_PIN = 9

# Create a DHT22 object with the specified pin number
TEMP_SENSOR = dht.DHT22(Pin(SENSOR_PIN))

# Create a client object to connect to Arduino IoT Cloud
client = ArduinoCloudClient(device_id=DEVICE_ID, username=DEVICE_ID, password=CLOUD_PASSWORD)

# Function to send temperature to Arduino IoT Cloud
def send_temperature():
    TEMP_SENSOR.measure()
    temperature = TEMP_SENSOR.temperature()
    print("Temperature:", temperature)
    
    # Send the temperature to Arduino IoT Cloud
    client["Temperature"] = temperature

# Connect to Arduino IoT Cloud
client.start()

# Loop indefinitely
while True:
    send_temperature()
    
    # Pause for 3 seconds before taking the next measurement
    sleep_ms(3000)

I can see the device "online" and I've created a thing called "Temperature" and a cloud variable (float) called "temperature"

This is the output of the log:

17:22:21.000 WiFi Connected ('192.168.0.22', '255.255.255.0', '192.168.0.1', '192.168.0.1')
17:22:24.000 RTC time set from NTP.
17:22:24.000 task: conn_task created.
17:22:24.000 Connecting to Arduino IoT cloud...
17:22:25.000 task: discovery created.
17:22:25.000 task: mqtt_task created.
17:22:25.000 Subscribe: b'/a/d/f23a4335-f4d1-413d-9cce-d6f3de68aed3/e/i'.
17:22:25.000 task: conn_task complete.
17:22:26.000 Subscribe: b'/a/t/e15e4d53-be7e-405f-a9df-95c46dc99020/e/i'.
17:22:26.000 Subscribe: b'/a/t/e15e4d53-be7e-405f-a9df-95c46dc99020/shadow/i'.
17:22:27.000 Device configured via discovery protocol.
17:22:27.000 task: discovery complete.

Hi @ssicard ! You need to register the cloud variable before you can use it using client.register("temperature", value=None). Make sure to call this before calling client.start(). Also, the variables are case sensitive afaik, so you need to update it with client["temperature"] = temperature because you used a lower case format on the cloud side when setting up the variable. Also you cannot have a while loop after the start() function because that already loops forever. You need to update the variable in a user task client.register(Task("user_task", on_run=user_task, interval=1.0)). Or you just register a callback function to read the new sensor value client.register("temperature", value=None, on_read= send_temperature, interval=3.0). I hope this helps.

Hi @sbhklr, thanks for the support! I followed your advice and modified the code as per your suggestion, I also separated the code in boot.py (just wifi) and main.py (arduino cloud), and it has been working stable for the past 24H.

Here's the code in case someone needs this in the future, I had a hard time understanding the "user_task" function and there are not much examples available (I'm new in coding and micropython):

Thanks again!

from machine import Pin
from time import sleep_ms
from arduino_iot_cloud import ArduinoCloudClient
from arduino_iot_cloud import Task
import dht
import logging

from secrets import DEVICE_ID
from secrets import CLOUD_PASSWORD


if __name__ == "__main__":
    # Configure the logger.
    # All message equal or higher to the logger level are printed.
    # To see more debugging messages, set level=logging.DEBUG.
    logging.basicConfig(
        datefmt="%H:%M:%S",
        format="%(asctime)s.%(msecs)03d %(message)s",
        level=logging.DEBUG,
    )


# Define sensor pin
SENSOR_PIN = 9

# Create a DHT22 object with the specified pin number
TEMP_SENSOR = dht.DHT22(Pin(SENSOR_PIN))

# Create a client object to connect to Arduino IoT Cloud
client = ArduinoCloudClient(device_id=DEVICE_ID, username=DEVICE_ID, password=CLOUD_PASSWORD)

# Function to send temperature to Arduino IoT Cloud
def user_task(client):
    try:
        TEMP_SENSOR.measure()
        temperature = TEMP_SENSOR.temperature()
        # Send the temperature to Arduino IoT Cloud
        client["temperature"] = temperature
    except Exception as e:
        logging.error(f"Error in user_task: {e}")


client.register(Task("user_task", on_run=user_task, interval=1.0))
client.register("temperature", value=None)

# Connect to Arduino IoT Cloud
client.start()

# Loop indefinitely

while True:
    # Pause for 3 seconds before taking the next measurement
    sleep_ms(3000)
2 Likes

Hi,

Thanks for sharing your experience. Just want to add some points from my own experience with Nano ESP32 and MicroPython. I followed the instructions from here and here with no success whatsoever. All I got was connection error code '5' (indicating wrong secret key or device id). Spent 6 hours debugging with no success.
Following day started googling and found this post. Re-tried connecting the Nano ESP32 and vola - the code that was not working yesterday was now working without a glitch!
The only conclusion for me is that somehow registering a new device to Arduino Cloud took a while because exact the same code worked today while could not connect yesterday!
The other thing maybe worth mentioning is that I found confusing that the instructions here talk about 'secret key' and then in the code about 'CLOUD_PASSWORD' - which appear to be one and same thing.

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.