Cloud Variables
Learn how to configure and use variables in your Arduino Cloud sketches.
Overview
Variables are essential components of the Arduino Cloud and are created and configured inside a Thing.
A Cloud variable is synced between your Arduino board and the Arduino Cloud. If a variable is updated on your board (like reading a sensor), the Arduino Cloud will also receive this value. Similarly, if a board receives an update from the Cloud, the variable also updates on your board.
As long as your board maintains a connection to the Arduino Cloud, the variables will be updated.
In this article, we will cover:
- How to sync variables between your board and the Arduino 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 is done inside a Thing, starting with the "Add Variable" button. This will open a new window where you can do several configurations.
Variable Configuration
Inside a variable configuration, we have several options:
- Name: a friendly name for your variable. No spaces or special characters allowed (except underscores).
- (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
- Basic: e.g.
- 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
by default).0
- Periodically: variable synchronizes every
seconds.x
- On Change: variable synchronizes whenever value changes (threshold is
Automatic Sketch Generation
Any variables you add will be automatically added to your thingProperties file, which contains any configurations made inside your Thing.
E.g. adding an integer variable called
test_value
, allows you to use it in your sketch without defining it.1test_value = 1;
Read more about it in the IoT Sketches section.
Callback 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}
Cloud Updates
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 of how to use the
millis()
function:1unsigned long previousMillis = 0;2const long interval = 1000; //milliseconds3
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 second15 //without blocking the program and the Cloud update16 }17}
Note that a variable's sync between a board and the Cloud is limited to two messages per second (500ms)
Variable Synchronisation
It is possible to sync (link) one or many variables across different Things, a feature that enables bi-directional communication between devices, without writing a single line of code!
To enable variable synchronization, create a new variable, and click on the "Sync with other Things" option.
Then select the variables you want to synchronize. They need to be of the same type (you can't link an integer to a boolean for example).
Whenever one variable updates, any variables added to the synchronisation will also update. In the graphic below we demonstrate how two Things could be set up:
is synced withswitch_1
. This is a typical remote light switch.light_1
variables are not linked.temperature
is synced withfan_control
. This could be a potentiometer that remotely controls the speed of a fan.fan_speed
For more details on this feature, check out the Device to Device tutorial.
Variable Lifecycle
Cloud variables are only synced with the Arduino Cloud during the Synchronized status. When we are in a different state, any change to the variable is local and will be overridden by the Arduino Cloud value as soon as it gets Synchronized.
A variable can be in any of the following stages:
- Disconnected - The variable has the local value. Any modification to the value will be overridden once Synchronized.
- Connecting - The variable has the local value. Any modification to the value will be overridden once Synchronized.
- Connected - The variable has the local value. Any modification to the value will be overridden once Synchronized.
- Synchronized - The variable is synced with the Cloud.
- If the value is changed locally, it is populated to the Cloud.
- If the value is changed in the Cloud via a dashboard or variable sync, the local value is updated (only for Read Write variables).
For callbacks & events depending on what status the variable is in, check out the Events & Callbacks section.
Cloud Variable List
Cloud variables are divided into three categories: basic, specialized and complex types. Below you will find all available variables that you can create.
Basic Types
All available basic variables are listed below:
Type | Declaration |
---|---|
Boolean |
|
Character String |
|
Floating Point Number |
|
Integer Number |
|
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.
Type | Declaration | Wrapped data type |
---|---|---|
Acceleration |
|
|
Angle |
|
|
Area |
|
|
Capacitance |
|
|
Contact Sensor |
|
|
Counter |
|
|
Data Rate |
|
|
Electric Current |
|
|
Electric Potention |
|
|
Electric Resistance |
|
|
Energy |
|
|
Flow Rate |
|
|
Force |
|
|
Frequency |
|
|
Heart Rate |
|
|
Information Content |
|
|
Length |
|
|
Light |
|
|
Logarithmic Quantity |
|
|
Luminance |
|
|
Luminous Flux |
|
|
Luminous Intensity |
|
|
Mass |
|
|
Motion Sensor |
|
|
Percentage |
|
|
Power |
|
|
Pressure |
|
|
Relative Humidity |
|
|
Smart Plug |
|
|
Switch |
|
|
CloudTemperature |
|
|
Temperature Sensor |
|
|
Time |
|
|
Velocity |
|
|
Volume |
|
|
Complex Types
The following variable types hold multiple values internally and are used to represent more complex data. To access such values, methods are provided.
CloudSchedule
CloudSchedule
is used to check for an active state or to retrieve the timestamp.Description | Type | Read value |
---|---|---|
Check for active state |
|
|
From (start date) |
|
|
To (end date)* |
|
|
Length of Timestamp |
|
|
*If no end date is selected, the value is defaulted to
0
.DimmedLight
Declared as
CloudDimmedLight x;
Property | Type | Read value | Set value |
---|---|---|---|
Brightness | (0-100) |
|
|
Switch |
|
|
|
ColoredLight
Declared as
CloudColoredLight x;
Property | Type | Read value | Set value |
---|---|---|---|
Switch |
|
|
|
Hue | (0-360) |
|
|
Saturation | (0-100) |
|
|
Brightness | (0-100) |
|
|
Color | (0-255) |
|
|
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.Property | Type | Read value | Set value |
---|---|---|---|
Hue | (0-360) |
|
|
Saturation | (0-100) |
|
|
Brightness | (0-100) |
|
|
Color | (0-255) |
|
|
To set the color, we can assign the CloudColor variable directly to float variables
x = {hue,saturation,brightness}
, or use 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)
.Property | Type | Read value | Set value |
---|---|---|---|
Latitude |
|
| This variable is ready only |
Longitude |
|
| This variable is ready only |
The format of the
and lat
is in Decimal Degrees (DD), for example lon
, 41.40338
.2.17403
Television
Declared as
CloudTelevision x;
Property | Type | Read Value | Set value |
---|---|---|---|
Switch |
|
|
|
Volume | (0-100) |
|
|
Mute |
|
|
|
PlaybackCommands | (FastForward, Next, Pause, Play, Previous, Rewind, StartOver, Stop) |
|
|
Input | (Up to 60 values such as HDMI1, HDMI2, DVD, GAME...etc.) |
|
|
Channel |
|
|
|
Examples
Here are some examples of how to use the variables in a sketch:
Basic Types
The example below shows how to use some of the basic types. Remember that Cloud variables are configured in the Arduino Cloud, and generated into your Thing's
thingProperties.h
file.In this example, we are using the following Cloud variables:
- boolean.buttonSwitch
- int.sensorVal
- string.messageString
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 found7 delay(1500); 8
9 // Defined in thingProperties.h10 initProperties();11
12 // Connect to Arduino Cloud13 ArduinoCloud.begin(ArduinoIoTPreferredConnection);14 setDebugMessageLevel(2);15 ArduinoCloud.printDebugInfo();16}17
18void loop() {19 ArduinoCloud.update();20
21 sensorVal = analogRead(A0); //int example22
23 if(buttonSwitch){ //bool example24 digitalWrite(LED_BUILTIN, HIGH);25 messageString = "LED ON!"; //String example26 }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 ArduinoGraphics3
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 found10 delay(1500); 11
12 // Defined in thingProperties.h13 initProperties();14
15 // Connect to Arduino Cloud16 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 - 25526 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 remote controller and save them in arrays of unsigned integers. An IR transmitter is then used to send IR signals using the Arduino Cloud.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 found23 delay(1500); 24
25 // Defined in thingProperties.h26 initProperties();27
28 // Connect to Arduino Cloud29 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 changed69 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 changed90 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 changed103 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 changed126 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 Cloud supports a limited amount of variables, see the list below:
- Colored Light -
andbool
(complex type).float
- Dimmed Light -
andbool
(complex type).float
- Television -
andbool
(complex type)int
- Contact Sensor -
bool
- Light -
bool
- Motion Sensor -
bool
- Smart Plug -
bool
- Switch -
bool
- Temperature Sensor -
float
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 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 Cloud.
Suggest changes
The content on docs.arduino.cc is facilitated through a public GitHub repository. If you see anything wrong, you can edit this page here.
License
The Arduino documentation is licensed under the Creative Commons Attribution-Share Alike 4.0 license.