hero

IoT Cloud Variables

Learn how to configure and use variables in your Arduino IoT Cloud sketches.

Overview

An essential component of the Arduino Cloud is a cloud variable.

A cloud variable is synced between your Arduino board and the Arduino IoT Cloud. If a variable is updated on your board (like reading a sensor), the Arduino Cloud will also receive this value. Similarly, if you update a variable from the cloud, it also updates on your board.

As long as your board maintains connection to the Arduino IoT Cloud, variables can be updated.

In this article, we will cover:

  • How to sync variables between your board and the Arduino IoT Cloud.
  • Types of variables and list of available ones.
  • How to structure a sketch for optimal variable synchronization.
  • How to synchronize variables between devices.

Create and Configure Variables

Creating and configuring variables are done inside a Thing, starting with the "Add Variable" button.

Click on "Add Variable"
Click on "Add Variable"

Variable Configuration

Inside a variable configuration, we have several options:

  • Name: a friendly name for your variable. No spaces or special characters allowed.
  • (optional) Sync With Other Things: sync a variable with a variable from another Thing. Whenever one variable updates, the other will follow.
  • Type: type of variable. Choose between three categories.
    • Basic: e.g.
      float
      ,
      int
      ,
      String
      .
    • Specialized: e.g.
      CloudAcceleration
      ,
      CloudTemperature
      ,
      CloudFrequency
      .
    • Complex: e.g.
      CloudColor
      ,
      CloudTelevision
      .
  • Declaration: the declaration of your variable. This is what you will use in a sketch.
  • Variable Permission:
    • Read & Write: variable can be updated from board and cloud.
    • Read Only: variable can only be updated from the board.
  • Variable Update Policy:
    • On Change: variable synchronizes whenever value changes (threshold is
      0
      by default).
    • Periodically: variable synchronizes every
      x
      seconds.

Automatic Sketch Generation

Whenever you add, change or remove a variable, a file called

thingProperties.h
is updated automatically. This is a configuration file that should always be included in your main sketch (it is generated automatically).

Since it is defined in

thingProperties.h
, you do not need to declare it in your
.ino
file.

Let's say we create an integer variable called

sensor_value
. To use this in a sketch, we simply use:

1sensor_value = analogRead(A0);

We do not need to define the variable anywhere, as it has already been configured in

thingProperties.h
.

Note that if you change a variable, you will need to upload the code to your board for the effects to come in change.

Generated Functions

When creating a variable with a Read & Write permission, a function is generated at the bottom of your sketch.

For example, a boolean variable named

button_switch
will generate a function called
void onButtonSwitch(){}
. This function executes every time the variable is changed from the cloud (through a dashboard).

You can for example implement an ON/OFF switch with the following code:

1void onButtonSwitch(){
2 if(button_switch){
3 digitalWrite(LED, HIGH);
4 }
5 else{
6 digitalWrite(LED, LOW);
7 }
8}

How is Data Synchronized?

Data between a board and the cloud synchronizes whenever the

ArduinoCloud.update()
function is executed. This is automatically included in your sketch, inside the
void loop()
.

It is a good practice to not use the

delay()
function in a cloud sketch. Please refer to the millis() function that can be used to create non-blocking delays.

Below is an example on how to use the

millis()
function:

1unsigned long previousMillis = 0;
2const long interval = 1000; //milliseconds
3
4void setup(){
5
6}
7
8void loop(){
9 unsigned long currentMillis = millis();
10
11 if (currentMillis - previousMillis >= interval) {
12 previousMillis = currentMillis;
13
14 //code here will update every 1 second
15 //without blocking the program and the cloud update
16 }

Note that a variable's sync between a board and the cloud is limited to two message per second (500ms)

Sync Variables Between Things

It is possible to sync one or many variables with each other, between Things. This is the easiest method available to connect two Arduino board devices, wirelessly.

This is done in the configuration of a variable, in the Sync With Other Things option.

To learn how to use this feature, read the Device to Device tutorial.

List of Variables

Cloud variables are divided into three categories: basic, specialized and complex types.

Basic Types

All available basic variables are listed below:

TypeDeclaration
Boolean
bool variableName;
Character String
String variableName;
Floating Point Number
float variableName;
Integer Number
int variableName;

Specialized Types

Specialized types are wrappers around basic types but declare the variable semantics more explicitly. This enables smarter integrations with third-party services (such as Alexa) and better visualization of widgets in dashboards.

You can use them just like a normal variable of the wrapped type, since they support assignment and comparison operators.

TypeDeclarationWrapped data type
Acceleration
CloudAcceleration variableName;
float
Angle
CloudAngle variableName;
float
Area
CloudArea variableName;
float
Capacitance
CloudCapacitance variableName;
float
Contact Sensor
CloudContactSensor variableName;
bool
Counter
CloudCounter variableName;
int
Data Rate
CloudDataRate variableName;
float
Electric Current
CloudElectricCurrent variableName;
float
Electric Potention
CloudElectricPotention variableName;
float
Electric Resistance
CloudElectricResistance variableName;
float
Energy
CloudEnergy variableName;
float
Flow Rate
CloudFlowRate variableName;
float
Force
CloudForce variableName;
float
Frequency
CloudFrequency variableName;
float
Heart Rate
CloudHeartRate variableName;
float
Information Content
CloudInformationContent variableName;
int
Length
CloudLength variableName;
float
Light
CloudLight variableName;
bool
Logarithmic Quantity
CloudLogarithmicQuantity variableName;
float
Luminance
CloudLuminance variableName;
float
Luminous Flux
CloudLuminousFlux variableName;
float
Luminous Intensity
CloudLuminousIntensity variableName;
float
Mass
CloudMass variableName;
float
Motion Sensor
CloudMotionSensor variableName;
bool
Percentage
CloudPercentage variableName;
float
Power
CloudPower variableName;
float
Pressure
CloudPressure variableName;
float
Relative Humidity
CloudRelativeHumidity variableName;
float
Smart Plug
CloudSmartPlug variableName;
bool
Switch
CloudSwitch variableName;
bool
CloudTemperature
CloudTemperature variableName;
float
Temperature Sensor
CloudTemperatureSensor variableName;
float
Time
CloudTime variableName;
float
Velocity
CloudVelocity variableName;
float
Volume
CloudVolume variableName;
float

Complex Types

The following variable types hold multiple values internally and are used to represent more complex data. In order to access such values, methods are provided.

CloudSchedule

CloudSchedule
is used to check for an active state or to retrieve the timestamp.

DescriptionTypeRead value
Check for active state
bool
x.isActive()
From (start date)
int
x.getCloudValue().frm
To (end date)*
int
x.getCloudValue().to
Length of Timestamp
int
x.getCloudValue().len

*If no end date is selected, value is defaulted to

0
.

DimmedLight

Declared as

CloudDimmedLight x;

PropertyTypeRead valueSet value
Brightness
float
(0-100)
x.getBrightness()
x.setBrightness()
Switch
bool
x.getSwitch()
x.setSwitch()

ColoredLight

Declared as

CloudColoredLight x;

PropertyTypeRead valueSet value
Switch
bool
x.getSwitch()
x.setSwitch()
Hue
float
(0-360)
x.getHue()
x.setHue()
Saturation
float
(0-100)
x.getSaturation()
x.setSaturation()
Brightness
float
(0-100)
x.getBrightness()
x.setBrightness()
Color
uint8_t
(0-255)
x.getRGB(r,g,b)
x.setRGB(r,g,b)

CloudColor

Declared as

CloudColor x;
.

To read the Color values, we can use the following method

Color colorValues = x.getValue();
. This will assign the hue, saturation, and brightness values to the
colorValues
variable.

PropertyTypeRead valueSet value
Hue
float
(0-360)
colorValues.hue
x = Color(hue,saturation,brightness)
Saturation
float
(0-100)
colorValues.sat
x = Color(hue,saturation,brightness)
Brightness
float
(0-100)
colorValues.bri
x = Color(hue,saturation,brightness)
Color
uint8_t
(0-255)
x.getRGB(r,g,b)
x.set(r,g,b)

To set the color, we can assign the CloudColor variable directly to float variables

x = {hue,saturation,brightness}
, or using the method
 x = Color(hue,saturation,brightness)
.

CloudLocation

Declared as

CloudLocation x;
.

To read the location values, we can use the following method

Location coordinates = x.getValue();
. This will assign the longitude and latitude values to the coordinates variable. If we want too access the values individually we can use
Serial.println(coordinates.lat)
and
Serial.println(coordinates.lon)
.

PropertyTypeRead valueSet value
Latitude
float
coordinates.lat
This variable is ready only
Longitude
float
coordinates.lon
This variable is ready only

The format of the

lat
and
lon
is in Decimal Degrees (DD), for example
41.40338
,
2.17403
.

Television

Declared as

CloudTelevision x;

PropertyTypeRead ValueSet value
Switch
bool
x.getSwitch()
x.setSwitch()
Volume
int
(0-100)
x.getVolume()
x.setVolume()
Mute
bool
x.getMute()
x.setMute()
PlaybackCommands
PlaybackCommands
(FastForward, Next, Pause, Play, Previous, Rewind, StartOver, Stop)
x.getPlaybackCommand()
x.setPlaybackCommand()
Input
InputValue
(Up to 60 values such as HDMI1, HDMI2, DVD, GAME...etc.)
x.getInput()
x.setInput()
Channel
int
x.getChannel()
x.setChannel()

Examples

Here are some examples of how to use the variables in a sketch:

Basic Types

The below example shows how to use some of the basic types. Remember that cloud variables are configured in the Arduino IoT cloud, and generated into your Thing's

thingProperties.h
file.

In this example, we are using the following cloud variables:

  • buttonSwitch
    - boolean.
  • sensorVal
    - int.
  • messageString
    - string.
1#include "thingProperties.h"
2
3void setup() {
4 // Initialize serial and wait for port to open:
5 Serial.begin(9600);
6 // This delay gives the chance to wait for a Serial mood without blocking if none is found
7 delay(1500);
8
9 // Defined in thingProperties.h
10 initProperties();
11
12 // Connect to Arduino IoT Cloud
13 ArduinoCloud.begin(ArduinoIoTPreferredConnection);
14 setDebugMessageLevel(2);
15 ArduinoCloud.printDebugInfo();
16}
17
18void loop() {
19 ArduinoCloud.update();
20
21 sensorVal = analogRead(A0); //int example
22
23 if(buttonSwitch){ //bool example
24 digitalWrite(LED_BUILTIN, HIGH);
25 messageString = "LED ON!"; //String example
26 }
27 else{
28 digitalWrite(LED_BUILTIN, LOW);
29 messageString = "LED OFF!";
30 }
31}

Colored Light

ColoredLight is a complex variable declared automatically in the

thingProperties.h
file as
CloudColoredLight variableName;
. The example below shows how the ColoredLight variable (declared with the variableName
cLight
) can be used and modified in the sketch. Note that the
onCLightChange()
function is automatically added and is triggered whenever the value of the Light variable is updated in the Cloud.

1#include <ArduinoGraphics.h>
2#include <Arduino_MKRRGB.h> // Arduino_MKRRGB depends on ArduinoGraphics
3
4#include "thingProperties.h"
5
6void setup() {
7 // Initialize serial and wait for port to open:
8 Serial.begin(9600);
9 // This delay gives the chance to wait for a Serial mood without blocking if none is found
10 delay(1500);
11
12 // Defined in thingProperties.h
13 initProperties();
14
15 // Connect to Arduino IoT Cloud
16 ArduinoCloud.begin(ArduinoIoTPreferredConnection);
17 setDebugMessageLevel(2);
18 ArduinoCloud.printDebugInfo();
19
20 if (!MATRIX.begin()) {
21 Serial.println("Failed to initialize MKR RGB shield!");
22 while (1);
23 }
24
25 // set the brightness, supported values are 0 - 255
26 MATRIX.brightness(10);
27}
28
29void loop() {
30 ArduinoCloud.update();
31}
32
33void onCLightChange() {
34 uint8_t r, g, b;
35 cLight.getValue().getRGB(r, g, b);
36
37 MATRIX.beginDraw();
38
39 if (cLight.getSwitch()) {
40 Serial.println("R:"+String(r)+" G:"+String(g)+ " B:"+String(b));
41 MATRIX.fill(r, g, b);
42 MATRIX.rect(0, 0, MATRIX.width(), MATRIX.height());
43 }else{
44 MATRIX.clear();
45 }
46
47 MATRIX.endDraw();
48}

Television

CloudTelevision is an automation variable declared automatically in the

thingProperties.h
file as
CloudTelevision variableName;
. The example below shows how the CloudTelevision variable (declared with the variableName
tv
) can be used and modified in the sketch. The example simulates a remote controller by using an IR receiver to read the signals sent from the a remote controller and save them in arrays of unsigned integers. An IR transmitter is then used to send IR signals using the Arduino IoT Cloud. To view the full documentation of the project, you can check this page.

Note that the

onTvChange()
function is automatically added and is triggered whenever the value of the tv variable is updated in the Cloud.

1#include "thingProperties.h"
2#include <IRremote.h>
3
4/******* SAVE DATA FROM IR RECEIVER ********/
5const unsigned int chan[9][67] = {};
6const unsigned int volUp[67] = {};
7const unsigned int chanUp[67] = {};
8const unsigned int onoff[67] = {};
9
10IRsend irsend;
11const int freq = 38;
12bool first;
13
14int prevChannel;
15int prevVolume;
16bool prevSwitch;
17bool prevMute;
18
19void setup() {
20 // Initialize serial and wait for port to open:
21 Serial.begin(9600);
22 // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
23 delay(1500);
24
25 // Defined in thingProperties.h
26 initProperties();
27
28 // Connect to Arduino IoT Cloud
29 ArduinoCloud.begin(ArduinoIoTPreferredConnection);
30 setDebugMessageLevel(2);
31 ArduinoCloud.printDebugInfo();
32
33 first = true;
34 pinMode(LED_BUILTIN, OUTPUT);
35}
36
37void loop() {
38 ArduinoCloud.update();
39}
40
41/******* HANDLING THE IR TRANSMITTER********/
42void sendIR(const unsigned int buf[]) {
43 digitalWrite(LED_BUILTIN, HIGH);
44 irsend.sendRaw(buf, 67, freq);
45 delay(300);
46 digitalWrite(LED_BUILTIN, LOW);
47}
48
49void onTvChange() {
50
51 Serial.println("==================");
52 Serial.println("Switch:"+String(tv.getSwitch()));
53 Serial.println("Volume:"+String(tv.getVolume()));
54 Serial.println("Channel:"+String(tv.getChannel()));
55 Serial.println("Mute:"+String(tv.getMute()));
56 Serial.println("==================");
57
58 if (first){
59 prevSwitch = tv.getSwitch();
60 prevVolume = tv.getVolume();
61 prevChannel = tv.getChannel();
62 prevMute = tv.getMute();
63 first = false;
64 return;
65 }
66
67
68 // Volume changed
69 if (tv.getVolume() > prevVolume) {
70 tv.setMute(false);
71 prevMute = false;
72 for (int k = prevVolume + 1 ; k<=tv.getVolume(); k++) {
73 sendIR(volUp);
74 Serial.println("Volume requested:"+String(tv.getVolume())+" Set:"+String(k));
75 }
76 prevVolume = tv.getVolume();
77 }
78 else if (tv.getVolume() < prevVolume) {
79 tv.setMute(false);
80 prevMute = false;
81 for (int k = prevVolume - 1; k>=tv.getVolume(); k--) {
82 sendIR(volDown);
83 Serial.println("Volume changed:"+String(tv.getVolume())+" Set:"+String(k));
84 }
85 prevVolume = tv.getVolume();
86 }
87
88
89 // Mute changed
90 if (tv.getMute() != prevMute && tv.getMute()) {
91 prevMute = tv.getMute();
92 sendIR(mute);
93 Serial.println("Mute changed:"+String(tv.getMute()));
94 }
95 else if (tv.getMute() != prevMute && !tv.getMute()) {
96 prevMute = tv.getMute();
97 sendIR(mute);
98 Serial.println("Mute changed:"+String(tv.getMute()));
99 }
100
101
102 // Channel changed
103 if (tv.getChannel() != prevChannel) {
104 int newChannel = tv.getChannel();
105 if (newChannel > 0 && newChannel < 10) {
106 sendIR(chan[newChannel-1]);
107 } else if (newChannel > 9) {
108 if (newChannel > prevChannel) {
109 for (int ch = prevChannel; ch < newChannel; ch++) {
110 sendIR(chanUp);
111 Serial.println("Chan requested:"+String(newChannel)+" Set:"+String(ch));
112 }
113 } else if (newChannel < prevChannel) {
114 for (int ch = prevChannel; ch > newChannel; ch--) {
115 sendIR(chanDown);
116 Serial.println("Chan requested:"+String(newChannel)+" Set:"+String(ch));
117 }
118 }
119 }
120 prevChannel = newChannel;
121 Serial.println("Channel changed:"+String(tv.getChannel()));
122 }
123
124
125 // On/Off changed
126 if (tv.getSwitch() != prevSwitch) {
127 prevSwitch = tv.getSwitch();
128 if (tv.getSwitch()) {
129 sendIR(chan[6]);
130 } else {
131 sendIR(onoff);
132 }
133 Serial.println("Switch changed:"+String(tv.getSwitch()));
134 }
135}

Alexa Variables

The integration between Alexa & Arduino IoT Cloud supports a limited amount of variables, see the list below:

Other variables used will not appear in the Amazon Alexa app.

To synchronize your Arduino Cloud with the Amazon Alexa service, you can check out the Arduino Cloud Alexa Tutorial.

Summary

In this article, we have covered how to use variables in the Arduino IoT Cloud, and what variables are available.

We have also shown some code examples and good practices to keep variable synchronization optimal, such as using the

millis()
function.

The use of cloud variables is almost identical to how you use variables in a regular sketch, with the exception that they are synchronized with the Arduino IoT Cloud.

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.