Connecting to Arduino IoT Cloud using MicroPython

Learn how to use the MicroPython library to connect to the Arduino IoT Cloud and control an LED.

Introduction

This tutorial guides you on how to use the MicroPython library to connect your Arduino device to the Arduino IoT Cloud.

Goals

The goals of this tutorial are:

  • Connect your Arduino device to your Wi-Fi® network.
  • Connect your Arduino device to the Arduino IoT Cloud.
  • Control an LED using the Arduino IoT Cloud.

Hardware & Software Needed

Setting Up Your Device and IoT Cloud

Before we start, make sure you have MicroPython installed on your board. If you haven't you can follow this tutorial. Then configure a Thing in the Arduino IoT Cloud consisting of two boolean variables called

led
and
ledSwitch
. To set up a Thing and a corresponding dashboard, please follow these two tutorials:

The resulting Thing and dashboard should look similar to the following:

Thing with two boolean variables.
Thing with two boolean variables.

Dashboard with an LED and a Switch widget.
Dashboard with an LED and a Switch widget.

Also, your device needs to be registered. Follow the flow "Any Device" ("Manual") when clicking Add in the "Devices" tab.

Dialog prompting to select setup flow
Dialog prompting to select setup flow

Give your board the desired name.

Give your device a name of your choice.
Give your device a name of your choice.

Eventually write down the Device ID / Secret Key pair that you will need to connect your device to Arduino IoT Cloud.

The connection credentials to be written down.
The connection credentials to be written down.

You will obtain a pair of device id and device key after registration. Store these details, along with your Wi-Fi® credentials, in a

secrets.py
file. Here is an example of how
secrets.py
should look like:

1WIFI_SSID = "myNetwork" # Network SSID
2WIFI_PASSWORD = "passwordForWiFi" # Network key
3DEVICE_ID = b"ef77wer88-0432-4574-85e1-54e3d5cac861"
4CLOUD_PASSWORD = b"TQHFHEKKKLSYMPB1OZLF"

This file should be copied over to the flash drive that mounts when MicroPython boots. To do so you can use the file manager tool in Arduino Lab for MicroPython or drag & drop the file manually. Please note that the latter option is not recommended as the file system can potentially get corrupted when copying files manually.

After configuring your device, assign it to the thing that you created previously. This gives access permission to the registered board.

Installing The Library

To install the Arduino IoT Cloud (Micro)Python library on your board, you can use thy Python based tool

mpremote
. This requires Python to be installed. On macOS and Linux Python usually comes pre-installed. If it's not installed on your system you may download it from here. Then, to install
mpremote
you can use pip:

1$ pip install mpremote

Run

mpremote connect list
to retrieve the serial number of your device. The output will look similar to this:

1/dev/cu.usbmodem3871345733302 335B34603532 2341:055b Arduino Portenta Virtual Comm Port in HS Mode

Pass this serial number (the second value) to the install command:

1$ mpremote connect id:335B34603532 mip install github:arduino/arduino-iot-cloud-py

This will install the library and all required dependencies on the board. Another option is to manually copy the files from the library's repository to the board's file system. It's good practice to put those files into a folder called

lib
to have the files organized neatly.

Programming the Board

Here is the example code to copy and paste into your sketch. It connects your device

1from machine import Pin
2import time
3import network
4import logging
5from arduino_iot_cloud import ArduinoCloudClient
6
7from secrets import WIFI_SSID
8from secrets import WIFI_PASSWORD
9from secrets import DEVICE_ID
10from secrets import CLOUD_PASSWORD
11
12led = Pin("LEDB", Pin.OUT) # Configure the desired LED pin as an output.
13
14def on_switch_changed(client, value):
15 # Toggles the hardware LED on or off.
16 led.value(not value)
17
18 # Sets the value of the cloud variable "led" to the current state of the LED
19 # and thus mirrors the hardware state in the cloud.
20 client["led"] = value
21
22def wifi_connect():
23 if not WIFI_SSID or not WIFI_PASSWORD:
24 raise (Exception("Network is not configured. Set SSID and passwords in secrets.py"))
25 wlan = network.WLAN(network.STA_IF)
26 wlan.active(True)
27 wlan.connect(WIFI_SSID, WIFI_PASSWORD)
28 while not wlan.isconnected():
29 logging.info("Trying to connect. Note this may take a while...")
30 time.sleep_ms(500)
31 logging.info(f"WiFi Connected {wlan.ifconfig()}")
32
33if __name__ == "__main__":
34 # Configure the logger.
35 # All message equal or higher to the logger level are printed.
36 # To see more debugging messages, set level=logging.DEBUG.
37 logging.basicConfig(
38 datefmt="%H:%M:%S",
39 format="%(asctime)s.%(msecs)03d %(message)s",
40 level=logging.INFO,
41 )
42
43 # NOTE: Add networking code here or in boot.py
44 wifi_connect()
45
46 # Create a client object to connect to the Arduino IoT cloud.
47 # For MicroPython, the key and cert files must be stored in DER format on the filesystem.
48 # Alternatively, a username and password can be used to authenticate:
49 client = ArduinoCloudClient(device_id=DEVICE_ID, username=DEVICE_ID, password=CLOUD_PASSWORD)
50
51 # Register cloud objects.
52 # Note: The following objects must be created first in the dashboard and linked to the device.
53 # This cloud object is initialized with its last known value from the cloud. When this object is updated
54 # from the dashboard, the on_switch_changed function is called with the client object and the new value.
55 client.register("ledSwitch", value=None, on_write=on_switch_changed, interval=0.250)
56
57 # This cloud object is updated manually in the switch's on_write_change callback to update the LED state in the cloud.
58 client.register("led", value=None)
59
60 # Start the Arduino IoT cloud client.
61 client.start()

Explanations:

  • wifi_connect()
    - Connects to your local Wi-Fi® using the credentials specified in secrets.py.
  • client.register
    - Registers a variable that will be synced with the cloud.
  • on_switch_changed
    - Is the callback that gets executed when the
    ledSwitch
    variable is changed by toggling the switch on the cloud dashboard. This function in turn toggles the on-board LED and updates the cloud variable
    led
    that reflects the state of the on-board LED to be displayed in the cloud dashboard.
  • client.start()
    - Enters a loop that runs as long as the board is connected to the cloud and synchronises data as it runs.

Testing It Out

Open Arduino Lab for MicroPython and connect to your board. Pasting the above code and run the script. Then open your Arduino IoT Cloud dashboard. You should see the registered "ledSwitch" and "led" widgets. Toggle the "ledSwitch", and the LED on your Arduino board should light up accordingly. The state of the "led" variable should also change, mirroring the state of the physical LED.

Troubleshoot

If the code is not working, there are some common issues we can troubleshoot:

  • Make sure MicroPython >= 1.2 is installed on your board.
  • Check the Wi-Fi® credentials in the
    secrets.py
    file.
  • Ensure the device ID and Cloud password in the
    secrets.py
    file match with what is registered on the IoT Cloud.
  • Make sure your IoT Cloud Thing is correctly set up and your device is assigned to it.

Conclusion

This tutorial has guided you through the process of connecting your Arduino device to the Arduino IoT Cloud using MicroPython. You learned how to install the necessary library, set up your device, and control an LED via the IoT Cloud. This opens up possibilities for more complex applications, as you can control and monitor your Arduino device remotely.

Tutorial Toolbox

Contribute to Arduino

Join the community and suggest improvements to this article via GitHub. Make sure to read out contribution policy before making your pull request.

Missing something?

Check out our store and get what you need to follow this tutorial.

Suggest Changes

The content on docs.arduino.cc is facilitated through a public GitHub repository. You can read more on how to contribute in the contribution policy.