Skip to content

Commit dcdf5e2

Browse files
authored
Merge pull request #1061 from arduino/sebromero/upython-lib-tutorial
[AE-75] Add tutorial for IoT Cloud with MicroPython
2 parents 8f2700a + 4ca74e5 commit dcdf5e2

File tree

6 files changed

+192
-0
lines changed

6 files changed

+192
-0
lines changed
225 KB
Loading
191 KB
Loading
302 KB
Loading
378 KB
Loading
318 KB
Loading
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
1+
---
2+
title: 'Connecting to Arduino IoT Cloud using MicroPython'
3+
description: 'Learn how to use the MicroPython library to connect to the Arduino IoT Cloud and control an LED.'
4+
tags:
5+
- IoT
6+
- MicroPython
7+
author: 'Sebastian Romero'
8+
libraries:
9+
- name: Arduino IoT Cloud Python
10+
url: https://github.com/arduino/arduino-iot-cloud-py
11+
---
12+
13+
## Introduction
14+
15+
This tutorial guides you on how to use the MicroPython library to connect your Arduino device to the Arduino IoT Cloud.
16+
17+
## Goals
18+
19+
The goals of this tutorial are:
20+
21+
- Connect your Arduino device to your Wi-Fi® network.
22+
- Connect your Arduino device to the Arduino IoT Cloud.
23+
- Control an LED using the Arduino IoT Cloud.
24+
25+
## Hardware & Software Needed
26+
27+
- [Arduino Lab for MicroPython](https://labs.arduino.cc/en/labs/micropython)
28+
- [Arduino GIGA R1 WiFi](/hardware/giga-r1-wifi) or [Portenta H7](/hardware/portenta-h7)
29+
- MicroPython >= 1.2 installed on your Arduino device (download firmware [here](/micropython/#firmware)).
30+
31+
32+
33+
## Setting Up Your Device and IoT Cloud
34+
35+
Before we start, make sure you have MicroPython installed on your board. If you haven't you can follow [this tutorial](https://docs.arduino.cc/micropython/basics/board-installation). Then configure a Thing in the [Arduino IoT Cloud](https://create.arduino.cc/iot/) consisting of two boolean variables called `led` and `ledSwitch`. To set up a Thing and a corresponding dashboard, please follow these two tutorials:
36+
37+
- [IoT Cloud Variables](https://docs.arduino.cc/arduino-cloud/getting-started/cloud-variables)
38+
- [IoT Cloud Dashboards & Widgets](https://docs.arduino.cc/arduino-cloud/getting-started/dashboard-widgets)
39+
40+
The resulting Thing and dashboard should look similar to the following:
41+
42+
![Thing with two boolean variables.](./assets/thing.png)
43+
44+
![Dashboard with an LED and a Switch widget.](./assets/dashboard.png)
45+
46+
Also, your device needs to be registered. Follow the flow "Any Device" ("Manual") when clicking **Add** in the "Devices" tab.
47+
48+
![Dialog prompting to select setup flow](./assets/setup-device-prompt.png)
49+
50+
Give your board the desired name.
51+
52+
![Give your device a name of your choice.](./assets/set-device-name.png)
53+
54+
Eventually write down the Device ID / Secret Key pair that you will need to connect your device to Arduino IoT Cloud.
55+
56+
![The connection credentials to be written down.](./assets/get-key.png)
57+
58+
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:
59+
60+
```python
61+
WIFI_SSID = "myNetwork" # Network SSID
62+
WIFI_PASSWORD = "passwordForWiFi" # Network key
63+
DEVICE_ID = b"ef77wer88-0432-4574-85e1-54e3d5cac861"
64+
CLOUD_PASSWORD = b"TQHFHEKKKLSYMPB1OZLF"
65+
```
66+
67+
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.
68+
69+
After configuring your device, **assign** it to the thing that you created previously. This gives access permission to the registered board.
70+
71+
72+
73+
## Installing The Library
74+
75+
To install the Arduino IoT Cloud (Micro)Python library on your board, you first need to install `mpremote` if you haven't done it yet. You can install it using pip:
76+
77+
```bash
78+
$ pip install mpremote
79+
```
80+
81+
Run `mpremote connect list` to retrieve the serial number of your device. The output will look similar to this:
82+
83+
```
84+
/dev/cu.usbmodem3871345733302 335B34603532 2341:055b Arduino Portenta Virtual Comm Port in HS Mode
85+
```
86+
87+
Pass this serial number (the second value) to the install command:
88+
89+
```bash
90+
$ mpremote connect id:335B34603532 mip install github:arduino/arduino-iot-cloud-py
91+
```
92+
93+
This will install the library and all required dependencies on the board.
94+
95+
## Programming the Board
96+
97+
Here is the example code to copy and paste into your sketch. It connects your device
98+
99+
```python
100+
from machine import Pin
101+
import time
102+
import network
103+
import logging
104+
from arduino_iot_cloud import ArduinoCloudClient
105+
106+
from secrets import WIFI_SSID
107+
from secrets import WIFI_PASSWORD
108+
from secrets import DEVICE_ID
109+
from secrets import CLOUD_PASSWORD
110+
111+
led = Pin("LEDB", Pin.OUT) # Configure the desired LED pin as an output.
112+
113+
def on_switch_changed(client, value):
114+
# Toggles the hardware LED on or off.
115+
led.value(not value)
116+
117+
# Sets the value of the cloud variable "led" to the current state of the LED
118+
# and thus mirrors the hardware state in the cloud.
119+
client["led"] = value
120+
121+
def wifi_connect():
122+
if not WIFI_SSID or not WIFI_PASSWORD:
123+
raise (Exception("Network is not configured. Set SSID and passwords in secrets.py"))
124+
wlan = network.WLAN(network.STA_IF)
125+
wlan.active(True)
126+
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
127+
while not wlan.isconnected():
128+
logging.info("Trying to connect. Note this may take a while...")
129+
time.sleep_ms(500)
130+
logging.info(f"WiFi Connected {wlan.ifconfig()}")
131+
132+
if __name__ == "__main__":
133+
# Configure the logger.
134+
# All message equal or higher to the logger level are printed.
135+
# To see more debugging messages, set level=logging.DEBUG.
136+
logging.basicConfig(
137+
datefmt="%H:%M:%S",
138+
format="%(asctime)s.%(msecs)03d %(message)s",
139+
level=logging.INFO,
140+
)
141+
142+
# NOTE: Add networking code here or in boot.py
143+
wifi_connect()
144+
145+
# Create a client object to connect to the Arduino IoT cloud.
146+
# For MicroPython, the key and cert files must be stored in DER format on the filesystem.
147+
# Alternatively, a username and password can be used to authenticate:
148+
client = ArduinoCloudClient(device_id=DEVICE_ID, username=DEVICE_ID, password=CLOUD_PASSWORD)
149+
150+
# Register cloud objects.
151+
# Note: The following objects must be created first in the dashboard and linked to the device.
152+
# This cloud object is initialized with its last known value from the cloud. When this object is updated
153+
# from the dashboard, the on_switch_changed function is called with the client object and the new value.
154+
client.register("ledSwitch", value=None, on_write=on_switch_changed, interval=0.250)
155+
156+
# This cloud object is updated manually in the switch's on_write_change callback to update the LED state in the cloud.
157+
client.register("led", value=None)
158+
159+
# Start the Arduino IoT cloud client.
160+
client.start()
161+
162+
```
163+
164+
**Explanations:**
165+
166+
- `wifi_connect()` - Connects to your local Wi-Fi® using the credentials specified in secrets.py.
167+
- `client.register` - Registers a variable that will be synced with the cloud.
168+
- `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.
169+
- `client.start()` - Enters a loop that runs as long as the board is connected to the cloud and synchronises data as it runs.
170+
171+
172+
173+
## Testing It Out
174+
175+
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.
176+
177+
178+
179+
## Troubleshoot
180+
181+
If the code is not working, there are some common issues we can troubleshoot:
182+
183+
- Make sure MicroPython >= 1.2 is installed on your board.
184+
- Check the Wi-Fi® credentials in the `secrets.py` file.
185+
- Ensure the device ID and Cloud password in the `secrets.py` file match with what is registered on the IoT Cloud.
186+
- Make sure your IoT Cloud Thing is correctly set up and your device is assigned to it.
187+
188+
189+
190+
## Conclusion
191+
192+
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.

0 commit comments

Comments
 (0)