Language: EN

referencia-lenguaje-arduino

Reference for the Arduino Language Programmer

We present a reference for the Arduino language programmer, with the different instructions and statements available in the language, organized by categories and with an example of each case.

This reference is not a programming manual. It is a “cheat sheet” aimed at people with programming knowledge, which serves for quick learning, consultation, and compilation of the syntax of the Arduino language. If this is not your case, we recommend that you start by learning to program in C++ in one of the many free courses available on the Internet.

Operators and Comparators

Comparators

//x equal to y
x == y

//x not equal to y
x != y

//x less than y  
x < y 

//x greater than y
x > y

//x less than or equal to y
x <= y

//x greater than or equal to y
x >= y 

Arithmetic Operators

//assignment operator
a = b

//addition
a + b

//subtraction
a - b

//multiplication
a * b

//division
a / b

//modulo
a % b

Bitwise Operators

//binary and
a & b  

//binary or
a | b  

//binary xor
a ^ b  

//binary not
a ~ b  

//left shift
a << b 

//right shift
a >> b 

Compound Operators

//increment
a++

//decrement
a--

//compound addition
a += b

//compound subtraction
a -= b

//compound multiplication
a *= b

//compound division
a /= b

//compound and
a &= b

//compound or
a |= b

Boolean Operators

//not
!a

//and
a && b

//or
a || b

Access Operators

//dereference operation
*variable

//address operation
&variable

Declaration and Conversion of Variable Types

//empty type (only for functions)
void

Booleans

//boolean, false or true
boolean = false;

Integers

//integer, 16 bits, from -32,768 to 32,767
int var = 100;

//integer, 16 bits, from 0 to 65535 (except in Due, where they are 32 bits)
unsigned int var = 100;

//integer, 16 bits, from 0 to 65535
short var = 100;

//integer, 32 bits, from -2,147,483,648 to 2,147,483,647
long var = 100000L;

//integer, 32bits, from 0 to 4,294,967,295
unsigned long var = 100000L;

Floating Point

//floating point, 32 bits, from -3.4028235E+38 to 3.4028235E+38. Precision 6 digits
float var = 1.117;

//identical to float, except on Arduino Due where it is a 64-bit float
double var = 1.117;

Bytes

//8 bits, from 0 to 255
byte var = B10010;

//16 bits, unsigned, from 0 to 65535
word var = 10000;

Characters

//8 bits, from -128 to 127
char var = 'A';

//8 bits, from 0 to 255
unsigned char var = 240;

Conversion between variables

//convert to char
char(variable);

//convert to byte
byte(variable);

//convert to int
int(variable);

//convert to word
word(variable);

//convert to long
long(variable);

//convert to float
float(variable);

Variable Qualifiers

//STATIC
//Variables visible only inside a function,
//and whose value is maintained between calls to it.
static int  variable;

//CONST
//Variables whose value cannot be redefined after initialization
const float pi = 3.14;

//VOLATILE
//Variables in which the compiler is told not to store in the microprocessor's registers,
//but to force the update in memory. This is done when there is a possibility that the value of the variable may be
//modified by another process that runs concurrently with the current one
//(for example when using threads or interrupts)
volatile int variable = LOW;

Arrays

Array Creation

//declare array
int myArray[5];

//initialize array
int myArray[] = {2, 4, 8, 3, 6};

//declare and initialize array
int myArray[5] = {2, 4, -8, 3, 2};

Array Manipulation

//assign value to array element
myArray[0] = 10;

//get value of array element
x = myArray[4];

Text Strings

Texts as Character Arrays

char string1[15];
char string2[8]  = {'a', 'r', 'd', 'u', 'i', 'n', 'o'};
char string3[8]  = {'a', 'r', 'd', 'u', 'i', 'n', 'o', '\0'};
char string4[ ]  = "text";
char string5[8]  = "text";
char string6[15] = "text";

//array of strings
char* stringArray[]={"String 1", "String 2", "String 3",
"String 4", "String 5", "String 6"};

Texts as String Object

//text string literal
String txtMsg = "Hello";

//converting a char to String
String txtMsg =  String('a');

//converting a literal to String
String txtMsg =  String("Text");

//concatenating two literals to String
String txtMsg =  String("text1" + "text2");

Conditionals

Abbreviated Conditional

condition ? true : false;

IF Conditional

if (variable < 10)
{
  // action A
}

if (variable < 10)
{
  // action A
}
else
{
  // action B
}

if (variable < 10)
{
  // action A
}
else if (variable >= 100)
{
  // action B
}
else
{
  // action C
}

SWITCH / CASE OF Conditional

switch (variable) {
  case 1:
    // action A
    break;
  case 2:
    //  action B
    break;
  default: 
    // default case (optional)
}

Loops

FOR Loop

for (int i=0; i <= 100; i++){
  // action
} 

WHILE Loop

variable = 0;

while(variable < 100){
  // action
  variable++;
}

DO WHILE Loop

do
{
  // action
  variable++;
} while (variable < 100);

Mathematical Functions

Range Functions

//returns minimum between a and b
min(a,b);

//returns maximum between a and b
max(a,b);

//returns absolute value of a
abs(a);

//returns x restricted to (a,b)
constrain(x, a, b);

//linearly interpolates y between x1,y1 x2,y2
map(x, x1, x2, y1, y2);

Exponentiation

//returns a^b (both float type)
pow(a,b);

//returns square root of a
sqrt(a);

Random Numbers

//initializes the seed of the pseudo-random number generator
randomSeed(seed);

//returns a random number between a and b (both long type)
random(a, b);

Trigonometry

//returns the sine of a (a float type and in radians)
sin(a);

//returns the cosine of a (a float type and in radians)
cos(a);

//returns the tangent of a (a float type and in radians)
tan(a);

Bit and Byte Functions

//returns the least significant byte of a word or variable.
lowByte(variable);

//returns the most significant byte of a word
//(or the second least significant byte in larger variables)
highByte(variable);

//returns the nth bit of a variable x 
//(with bit 0 being the least significant)
bitRead(x, n);

//writes the nth bit of variable x with value b
//(with bit 0 being the least significant)
bitWrite(x, n,b );

//sets bit n of variable x to 1
bitSet(x, n);

//clears bit n of variable x to 0
bitClear(x, n);

//gets the value of bit n (identical to 2^n)
bit(n);

Text Functions

//returns the character at position 3 (identical to txtMsg[3];)
txtMsg.charAt(3);

//replaces the character at position 3 with "A" (identical to txtMsg[3]="A";)
txtMsg.setCharAt("A", 3);

//concatenates text 1 and text 2 (identical to text1=text1+text2;)
text1.concat("text2");

//returns the length of the string
txtMsg.length();

//returns the string converted to lowercase
txtMsg.toLowerCase();

//returns the string converted to uppercase
txtMsg.toUpperCase();

//removes spaces and incorrect characters
txtMsg.trim();

//returns the text string as an integer
txtMsg.toInt();

Comparison

//compares two strings. Returns 1 if text1 is greater than text2,
//0 if they are equal, and -1 otherwise 
text1.compareTo(text2);

//compares if two strings are equal (identical to text1==text2)
text1.equals(text2);

//compares if two strings are equal, ignoring case
text1.equalsIgnoreCase(text2);

Substrings

//returns a substring from position 3 to 10
txtMsg.substring(3, 10);

//checks if the string starts with "text", with offset 3
txtMsg.startsWith("text", 3);

//checks if the string ends with "text"
txtMsg.endsWith("text");

Search and Replace

//returns the index of the first occurrence of 'A',
//starting from the offset position
txtMsg.indexOf('A', offset);

//returns the index of the last occurrence of 'A'
//prior to the offset position
txtMsg.lastIndexOf('A', offset);

//replaces occurrences of "text1" with "text2"
txtMsg.replace("text1", "text2");

User Functions

Global Variables

int option=1;

int change(){
  option=4;
}

void setup(){
  Serial.begin(9600);
}

void loop(){
  change();
  Serial.print(option);  //displays 4
  delay(10000);
}

Passing Parameters by Value

int change(var){
  var=4;
}

void setup(){
  Serial.begin(9600);
}

void loop(){
  int option=1;
  change(option);
  Serial.print(option);  //displays 1
  delay(10000);
}

Passing Parameters by Reference

int change(int &var){
  var=4;
}

void setup(){
  Serial.begin(9600);
}

void loop(){
  int option=1;
  change(option);
  Serial.print(option);    //displays 4
  delay(10000);
}

Passing Parameters by Pointer

int change(int* var){
  *var=4;
}

void setup(){
  Serial.begin(9600);
}

void loop(){
  int option=1;
  change(&option);
  Serial.print(option);    //displays 4
  delay(10000);
}

Return Values

int change(){
  int var=4;
  return var;
}

void setup(){
  Serial.begin(9600);
}

void loop(){
  int option=1;
  option=change();
  Serial.print(option);    //displays 4
  delay(10000);
}

Advanced Data Types (Enum / Struct / Typedef)

Enumerations

//declaration
enum myEnumeration {
  option1,
  option2,
  option3
};

//example of use
myEnumeration variable = option2;

if (variable==option2){
  //action
}

Structures

//declaration
struct myStructure
{
   int  field1;
   int  field2;
   char field3;
};

//example of use
struct myStructure variable;

variable.field1=10;

User-defined Data Type Definition

//declarations
typedef int newtype;
typedef enum myEnumeration newtype;
typedef struct myStructure newtype;

//example of use
newtype variable;

Classes

Example of Class Usage

class MyRobot;

//class definition example
class MyRobot
{
public:
  void greet();   //displays "Hello"
  void incCount();   //increments counter
  int  getCount();   //returns counter
  void sayCount();   //displays counter value
  void setCount(int); //initializes counter to a value
private:
  int count=0;     //private counter variable
};

//displays "Hello"
void MyRobot::greet(){
  Serial.println("Hello");
}

void MyRobot::incCount(){
  this->count++;
}

//returns counter
int MyRobot::getCount(){
  return this->count;
}

//displays counter value
void MyRobot::sayCount(){
  Serial.println(this->count);
}

//initializes counter to a value
void MyRobot::setCount(int _count){
  this->count=_count;
}

MyRobot robot;
void setup(){
  Serial.println("Initializing");
  Serial.begin(9600); 

  robot.greet();   //displays hello
}

void loop(){
  robot.incCount();  //increments counter
  robot.sayCount();  //displays value
  delay(1000);
}

Download the Code

All the code from this post is available for download on Github. github-full