C++/Arduino Cheat Sheet: Variables
C++/Arduino Cheat Sheet: Variables
Variables
In many high level languages you dont explicitly define the type of you variables. For example in
javascript you might write
var x = 1;
Or in python just
x=1
In C++ variables have definite types. This is important when introducing the variable for the first
time, which is also known as declaring. In the following well shortly introduce all the types you
need to know in this workshop.
After declaring the variables you can use the variables as usual.
For example
int i = 1;
i = i + 3;
int
int is short for integer, an even number. For example you might write
int x = 0;
float
Float is short for floating point, and technicalities aside is just a type for a decimal number.
float pi = 3.14;
bool
Bool, or boolean, contains a true/false value.
void
You dont really need to know about void, but it can been seen in every project. The Arduino setup
and loop functions return a void type variable - which means they return nothing.
String
String isnt an actual C++ type, but a class of the Arduino development environment. This is nice,
because C++ strings are pretty much a pain. You can declare a String just by writing
Sometimes the code interpreter (aka compiler) might confuse a string as a C++ string. This is likely
if you try to combine several strings which are not explicitly Strings.
For example
Is asking for trouble. Instead you can use the String constructor method
#define
#Define isnt exactly a variable. However, in Arduino applications it is often used as a way to define
some settings that are constant in the program. In addition to some technical benefits it also makes
the code easier to read as well as eases modifications.
In the following example we define the keyword redLed to be 2 and later use it to turn the led on.
#define redLed 2
.
.
.
digitalWrite(redLed, HIGH);
If we ever decide to switch the led to a different GPIO pin it would be really easy to just change the
definition.
Brackets and conditions
If, else, else if, loops etc. use brackets. For example
if (a == b) {
goHome();
}
else if (b == c) {
doSomethingElse();
}
else {
somethingDifferent();
}
To combine conditions use && for and, || for or and ! for negation. For example
The semicolon
Lines end in semicolons. Just remember this and your code will compile.
Printing to console
What about console.log or print? Well since your code isnt running on your PC you have to debug
through the serial port (through the USB cable).