Code basics – Arduino C
The Arduino uses a slightly reduced C/C++ programming language. In this recipe, we will remember a few basics of C/C++.
Getting ready
Ensure that you have the Arduino IDE running on a computer.
How to do it…
Here is a simple example of basic Arduino C/C++ manipulating two variables:
// Global Variables int var1 = 10; int var2 = 20; void setup() { // Only execute once when the Arduino boots var2 = 5; // var2 becomes 5 once the Arduino boots } void loop(){ // Code executes top-down and repeats continuously if (var1 > var2){ // If var1 is greater than var2 var2++; // Increment var2 by 1 } else { // If var1 is NOT greater than var2 var2 = 0; // var2 becomes 0 } }
How it works…
The code plays with two integer variables. Here we have a code breakdown to better explain each step.
First, we declared two global variables—var1
and var2
—and we set them to the values of 10
and 20
respectively.
// Global Variables int var1 = 10; int var2 = 20;
When the Arduino boots, it first allocates the global variables into memory. In the setup()
function, we change the value of var2
to 5
:
void setup() { // Only execute once when the Arduino boots var2 = 5; // var2 becomes 5 once the Arduino boots }
After the Arduino allocates the global variables, it executes the code inside the setup()
function once. Following this, the loop()
function will execute repeatedly. Inside, we have an if
condition that will play with the values of var2
. If var1
is greater than var2
, we increase var2
by one. Eventually, var1
will not be greater than var2
, and then we set var2
to 0
. This will result in an infinite adding and equaling of var2
.
This is one example on how the Arduino executes the code in its two main functions.
See also
Continue the Arduino code basics with the following recipe, Code basics – Arduino pins.