Syntax
difference = operand1 - operand2;
Parameters
difference: variable. Allowed data types: int, float, double, byte, short, long.
operand1: variable or constant. Allowed data types: int, float, double, byte, short, long.
operand2: variable or constant. Allowed data types: int, float, double, byte, short, long.
Example Code
int a = 5;
int b = 10;
int c = 0;
c = a - b;  // the variable 'c' gets a value of -5 after this statement is executed
Notes and Warnings
The subtraction operation can overflow if the result is smaller than that which can be stored in the data type (e.g. subtracting 1 from an integer with the value -32,768 gives 32,767).


If one of the numbers (operands) are of the type float or of type double, floating point math will be used for the calculation.
If the operands are of float / double data type and the variable that stores the difference is an integer, then only the integral part is stored and the fractional part of the number is lost.
float a = 5.5;
float b = 6.6;
int c = 0;
c = a - b;  // the variable 'c' stores a value of -1 only as opposed to the expected difference of -1.1
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Sketch
            > Setup

setup()
          [Sketch]

Description
The setup() function is called when a sketch starts. Use it to initialize variables, pin modes, start using libraries, etc. The setup() function will only run once, after each powerup or reset of the Arduino board.
Example Code
int buttonPin = 3;


Example Code
int buttonPin = 3;
void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
}
void loop() {
  // ...
}
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Sketch
            > Loop

loop()
          [Sketch]

Description
After creating a setup() function, which initializes and sets the initial values, the loop() function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond. Use it to actively control the Arduino board.
Example Code


Example Code
int buttonPin = 3;
// setup initializes serial and the button pin
void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
}
// loop checks the button pin each time,
// and will send serial if it is pressed
void loop() {
  if (digitalRead(buttonPin) == HIGH) {
    Serial.write('H');
  }
  else {
    Serial.write('L');
  }
  delay(1000);
}
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Boolean operators
            > Logicalnot

!
          [Boolean Operators]

Description
Logical NOT results in a true if the operand is false and vice versa.
Example Code
This operator can be used inside the condition of an if statement.
if (!x) { // if x is not true
  // statements
}


if (!x) { // if x is not true
  // statements
}
It can be used to invert the boolean value.
x = !y; // the inverted value of y is stored in x
Notes and Warnings
The bitwise not ~ (tilde) looks much different than the boolean not ! (exclamation point or "bang" as the programmers say) but you still have to be sure which one you want where.
See also
LANGUAGE ~ Bitwise NOT


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Boolean operators
            > Logicaland

&&
          [Boolean Operators]

Description
Logical AND results in true only if both operands are true.
Example Code
This operator can be used inside the condition of an if statement.
if (digitalRead(2) == HIGH && digitalRead(3) == HIGH) { // if BOTH the switches read HIGH


// statements
}
Notes and Warnings
Make sure you don’t mistake the boolean AND operator, && (double ampersand) for the bitwise AND operator & (single ampersand). They are entirely different beasts.
See also
LANGUAGE & (Bitwise AND)


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Boolean operators
            > Logicalor

||
          [Boolean Operators]

Description
Logical OR results in a true if either of the two operands is true.
Example Code
This operator can be used inside the condition of an if statement.
if (x > 0 || y > 0) { // if either x or y is greater than zero


// statements
}
Notes and Warnings
Do not confuse the boolean || (double pipe) operator with the bitwise OR operator | (single pipe).
See also
LANGUAGE | Bitwise OR


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Bitwise operators
            > Bitwisenot

~
          [Bitwise Operators]

Description


~
          [Bitwise Operators]

Description
The bitwise NOT operator in C++ is the tilde character ~. Unlike & and |, the bitwise NOT operator is applied to a single operand to its right. Bitwise NOT changes each bit to its opposite: 0 becomes 1, and 1 becomes 0.
In other words:
0  1    operand1
-----
1  0   ~operand1
Example Code
int a = 103;  // binary:  0000000001100111
int b = ~a;   // binary:  1111111110011000 = -104
Notes and Warnings


Notes and Warnings
You might be surprised to see a negative number like -104 as the result of this operation. This is because the highest bit in an int variable is the so-called sign bit. If the highest bit is 1, the number is interpreted as negative. This encoding of positive and negative numbers is referred to as two’s complement. For more information, see the Wikipedia article on two’s complement.
As an aside, it is interesting to note that for any integer x, ~x is the same as -x - 1.
At times, the sign bit in a signed integer expression can cause some unwanted surprises.
See also
EXAMPLE BitMath Tutorial


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Bitwise operators
            > Bitshiftright

>>
          [Bitwise Operators]

Description
The right shift operator >> causes the bits of the left operand to be shifted right by the number of positions specified by the right operand.
Syntax
variable >> number_of_bits;
Parameters
variable: Allowed data types: byte, int, long.


Parameters
variable: Allowed data types: byte, int, long.
number_of_bits: a number that is < = 32. Allowed data types: int.
Example Code
int a = 40;     // binary: 0000000000101000
int b = a >> 3; // binary: 0000000000000101, or 5 in decimal
Notes and Warnings
When you shift x right by y bits (x >> y), and the highest bit in x is a 1, the behavior depends on the exact data type of x. If x is of type int, the highest bit is the sign bit, determining whether x is negative or not, as we have discussed above. In that case, the sign bit is copied into lower bits, for esoteric historical reasons:
int x = -16;  // binary: 1111111111110000
int y = 3;


int y = 3;
int result = x >> y;  // binary: 1111111111111110
This behavior, called sign extension, is often not the behavior you want. Instead, you may wish zeros to be shifted in from the left. It turns out that the right shift rules are different for unsigned int expressions, so you can use a typecast to suppress ones being copied from the left:
int x = -16;  // binary: 1111111111110000
int y = 3;
int result = (unsigned int)x >> y;  // binary: 0001111111111110
If you are careful to avoid sign extension, you can use the right-shift operator >> as a way to divide by powers of 2. For example:
int x = 1000;
int y = x >> 3; // integer division of 1000 by 8, causing y = 125.


See also
EXAMPLE BitMath Tutorial


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Bitwise operators
            > Bitshiftleft

<<
          [Bitwise Operators]

Description
The left shift operator << causes the bits of the left operand to be shifted left by the number of positions specified by the right operand.
Syntax
variable << number_of_bits;
Parameters
variable: Allowed data types: byte, int, long.


Parameters
variable: Allowed data types: byte, int, long.
number_of_bits: a number that is < = 32. Allowed data types: int.
Example Code
int a = 5;      // binary: 0000000000000101
int b = a << 3; // binary: 0000000000101000, or 40 in decimal
Notes and Warnings
When you shift a value x by y bits (x << y), the leftmost y bits in x are lost, literally shifted out of existence:
int x = 5;  // binary: 0000000000000101
int y = 14;
int result = x << y;  // binary: 0100000000000000 - the first 1 in 101 was discarded


If you are certain that none of the ones in a value are being shifted into oblivion, a simple way to think of the left-shift operator is that it multiplies the left operand by 2 raised to the right operand power. For example, to generate powers of 2, the following expressions can be employed:
   Operation  Result
   ---------  ------
    1 <<  0      1
    1 <<  1      2
    1 <<  2      4
    1 <<  3      8
    ...
    1 <<  8    256
    1 <<  9    512
    1 << 10   1024
    ...


1 << 10   1024
    ...
The following example can be used to print out the value of a received byte to the serial monitor, using the left shift operator to move along the byte from bottom(LSB) to top (MSB), and print out its Binary value:
// Prints out Binary value (1 or 0) of byte
void printOut1(int c) {
  for (int bits = 7; bits > -1; bits--) {
    // Compare bits 7-0 in byte
    if (c & (1 << bits)) {
      Serial.print("1");
    }
    else {
      Serial.print("0");
    }
  }
}
See also
EXAMPLE BitMath Tutorial


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Bitwise operators
            > Bitwiseor

|
          [Bitwise Operators]

Description


|
          [Bitwise Operators]

Description
The bitwise OR operator in C++ is the vertical bar symbol, |. Like the & operator, | operates independently each bit in its two surrounding integer expressions, but what it does is different (of course). The bitwise OR of two bits is 1 if either or both of the input bits is 1, otherwise it is 0.
In other words:
0  0  1  1    operand1
0  1  0  1    operand2
----------
0  1  1  1    (operand1 | operand2) - returned result
Example Code
int a =  92;    // in binary: 0000000001011100
int b = 101;    // in binary: 0000000001100101


int b = 101;    // in binary: 0000000001100101
int c = a | b;  // result:    0000000001111101, or 125 in decimal.
One of the most common uses of the Bitwise OR is to set multiple bits in a bit-packed number.
// Note: This code is AVR architecture specific
// set direction bits for pins 2 to 7, leave PD0 and PD1 untouched (xx | 00 == xx)
// same as pinMode(pin, OUTPUT) for pins 2 to 7 on Uno or Nano
DDRD = DDRD | 0b11111100;
See also
LANGUAGE || Logical OR
EXAMPLE BitMath Tutorial


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Bitwise operators
            > Bitwisexor

^
          [Bitwise Operators]

Description


^
          [Bitwise Operators]

Description
There is a somewhat unusual operator in C++ called bitwise EXCLUSIVE OR, also known as bitwise XOR. (In English this is usually pronounced "eks-or".) The bitwise XOR operator is written using the caret symbol ^. A bitwise XOR operation results in a 1 only if the input bits are different, else it results in a 0.
Precisely,
0  0  1  1    operand1
0  1  0  1    operand2
----------
0  1  1  0    (operand1 ^ operand2) - returned result
Example Code
int x = 12;     // binary: 1100
int y = 10;     // binary: 1010
int z = x ^ y;  // binary: 0110, or decimal 6


int z = x ^ y;  // binary: 0110, or decimal 6
The ^ operator is often used to toggle (i.e. change from 0 to 1, or 1 to 0) some of the bits in an integer expression. In a bitwise XOR operation if there is a 1 in the mask bit, that bit is inverted; if there is a 0, the bit is not inverted and stays the same.
// Note: This code uses registers specific to AVR microcontrollers (Uno, Nano, Leonardo, Mega, etc.)
// it will not compile for other architectures
void setup() {
  DDRB = DDRB | 0b00100000;  // set PB5 (pin 13 on Uno/Nano, pin 9 on Leonardo/Micro, pin 11 on Mega) as OUTPUT
  Serial.begin(9600);
}
void loop() {


Serial.begin(9600);
}
void loop() {
  PORTB = PORTB ^ 0b00100000;  // invert PB5, leave others untouched
  delay(100);
}
See also
EXAMPLE BitMath Tutorial


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Bitwise operators
            > Bitwiseand

&
          [Bitwise Operators]

Description


&
          [Bitwise Operators]

Description
The bitwise AND operator in C++ is a single ampersand &, used between two other integer expressions. Bitwise AND operates on each bit position of the surrounding expressions independently, according to this rule: if both input bits are 1, the resulting output is 1, otherwise the output is 0.
Another way of expressing this is:
0  0  1  1    operand1
0  1  0  1    operand2
----------
0  0  0  1    (operand1 & operand2) - returned result
In Arduino, the type int is a 16-bit value, so using & between two int expressions causes 16 simultaneous AND operations to occur.
Example Code
In a code fragment like:
int a =  92;    // in binary: 0000000001011100


int a =  92;    // in binary: 0000000001011100
int b = 101;    // in binary: 0000000001100101
int c = a & b;  // result:    0000000001000100, or 68 in decimal.
Each of the 16 bits in a and b are processed by using the bitwise AND, and all 16 resulting bits are stored in c, resulting in the value 01000100 in binary, which is 68 in decimal.
One of the most common uses of bitwise AND is to select a particular bit (or bits) from an integer value, often called masking. See below for an example (AVR architecture specific).
PORTD = PORTD & 0b00000011;  // clear out bits 2 - 7, leave pins PD0 and PD1 untouched (xx & 11 == xx)
See also


See also
LANGUAGE && Logical AND
EXAMPLE BitMath Tutorial


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Control structure
            > Break

break
          [Control Structure]

Description
break is used to exit from a for, while or do…while loop, bypassing the normal loop condition. It is also used to exit from a switch case statement.
Example Code


Example Code
In the following code, the control exits the for loop when the sensor value exceeds the threshold.
int threshold = 40;
for (int x = 0; x < 255; x++) {
  analogWrite(PWMpin, x);
  sens = analogRead(sensorPin);
  if (sens > threshold) {     // bail out on sensor detect
    x = 0;
    break;
  }
  delay(50);
}
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Control structure
            > If

if
          [Control Structure]

Description
The if statement checks for a condition and executes the following statement or set of statements if the condition is 'true'.
Syntax
if (condition) {
  //statement(s)
}
Parameters
condition: a boolean expression (i.e., can be true or false).


}
Parameters
condition: a boolean expression (i.e., can be true or false).
Example Code
The brackets may be omitted after an if statement. If this is done, the next line (defined by the semicolon) becomes the only conditional statement.
if (x > 120) digitalWrite(LEDpin, HIGH);
if (x > 120)
digitalWrite(LEDpin, HIGH);
if (x > 120) {digitalWrite(LEDpin, HIGH);}
if (x > 120) {
  digitalWrite(LEDpin1, HIGH);
  digitalWrite(LEDpin2, HIGH);
}
// all are correct
Notes and Warnings
The statements being evaluated inside the parentheses require the use of one or more operators shown below.
Comparison Operators:
x == y (x is equal to y)
x != y (x is not equal to y)
x <  y (x is less than y)


x <  y (x is less than y)
x >  y (x is greater than y)
x <= y (x is less than or equal to y)
x >= y (x is greater than or equal to y)
Beware of accidentally using the single equal sign (e.g. if (x = 10) ). The single equal sign is the assignment operator, and sets x to 10 (puts the value 10 into the variable x). Instead use the double equal sign (e.g. if (x == 10) ), which is the comparison operator, and tests whether x is equal to 10 or not. The latter statement is only true if x equals 10, but the former statement will always be true.


This is because C++ evaluates the statement if (x=10) as follows: 10 is assigned to x (remember that the single equal sign is the (assignment operator)), so x now contains 10. Then the 'if' conditional evaluates 10, which always evaluates to TRUE, since any non-zero number evaluates to TRUE. Consequently, if (x = 10) will always evaluate to TRUE, which is not the desired result when using an 'if' statement. Additionally, the variable x will be set to 10, which is also not a desired action.
See also
LANGUAGE else


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Control structure
            > Else

else
          [Control Structure]

Description


> Else

else
          [Control Structure]

Description
The if…else allows greater control over the flow of code than the basic if statement, by allowing multiple tests to be grouped. An else clause (if at all exists) will be executed if the condition in the if statement results in false. The else can proceed another if test, so that multiple, mutually exclusive tests can be run at the same time.
Each test will proceed to the next one until a true test is encountered. When a true test is found, its associated block of code is run, and the program then skips to the line following the entire if/else construction. If no test proves to be true, the default else block is executed, if one is present, and sets the default behavior.
Note that an else if block may be used with or without a terminating else block and vice versa. An unlimited number of such else if branches are allowed.
Syntax


Syntax
if (condition1) {
  // do Thing A
}
else if (condition2) {
  // do Thing B
}
else {
  // do Thing C
}
Example Code
Below is an extract from a code for temperature sensor system
if (temperature >= 70) {
  // Danger! Shut down the system.
}
else if (temperature >= 60) { // 60 <= temperature < 70
  // Warning! User attention required.
}
else { // temperature < 60
  // Safe! Continue usual tasks.
}
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Control structure
            > For

for
          [Control Structure]

Description
The for statement is used to repeat a block of statements enclosed in curly braces. An increment counter is usually used to increment and terminate the loop. The for statement is useful for any repetitive operation, and is often used in combination with arrays to operate on collections of data/pins.


Syntax
for (initialization; condition; increment) {
  // statement(s);
}
Parameters
initialization: happens first and exactly once.
condition: each time through the loop, condition is tested; if it’s true, the statement block, and the increment is executed, then the condition is tested again. When the condition becomes false, the loop ends.
increment: executed each time through the loop when condition is true.
Example Code
// Dim an LED using a PWM pin
int PWMpin = 10;  // LED in series with 470 ohm resistor on pin 10
void setup() {
  // no setup needed
}
void loop() {
  for (int i = 0; i <= 255; i++) {
    analogWrite(PWMpin, i);
    delay(10);
  }
}
Notes and Warnings


delay(10);
  }
}
Notes and Warnings
The C++ for loop is much more flexible than for loops found in some other computer languages, including BASIC. Any or all of the three header elements may be omitted, although the semicolons are required. Also the statements for initialization, condition, and increment can be any valid C++ statements with unrelated variables, and use any C++ datatypes including floats. These types of unusual for statements may provide solutions to some rare programming problems.
For example, using a multiplication in the increment line will generate a logarithmic progression:
for (int x = 2; x < 100; x = x * 1.5) {
  println(x);
}
Generates: 2,3,4,6,9,13,19,28,42,63,94
Another example, fade an LED up and down with one for loop:
void loop() {


Another example, fade an LED up and down with one for loop:
void loop() {
  int x = 1;
  for (int i = 0; i > -1; i = i + x) {
    analogWrite(PWMpin, i);
    if (i == 255) {
      x = -1;  // switch direction at peak
    }
    delay(10);
  }
}
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Control structure
            > Goto

goto
          [Control Structure]

Description
Transfers program flow to a labeled point in the program
Syntax
label:
goto label; // sends program flow to the label
Example Code
for (byte r = 0; r < 255; r++) {


Example Code
for (byte r = 0; r < 255; r++) {
  for (byte g = 255; g > 0; g--) {
    for (byte b = 0; b < 255; b++) {
      if (analogRead(0) > 250) {
        goto bailout;
      }
      // more statements ...
    }
  }
}
bailout:
// more statements ...
Notes and Warnings
The use of goto is discouraged in C programming, and some authors of C programming books claim that the goto statement is never necessary, but used judiciously, it can simplify certain programs. The reason that many programmers frown upon the use of goto is that with the unrestrained use of goto statements, it is easy to create a program with undefined program flow, which can never be debugged.


With that said, there are instances where a goto statement can come in handy, and simplify coding. One of these situations is to break out of deeply nested for loops, or if logic blocks, on a certain condition.
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Control structure
            > Return

return
          [Control Structure]

Description
Terminate a function and return a value from a function to the calling function, if desired.
Syntax
return;
return value;
Parameters
value: Allowed data types: any variable or constant type.
Example Code
A function to compare a sensor input to a threshold


Example Code
A function to compare a sensor input to a threshold
int checkSensor() {
  if (analogRead(0) > 400) {
    return 1;
  }
  else {
    return 0;
  }
}
The return keyword is handy to test a section of code without having to "comment out" large sections of possibly buggy code.
void loop() {
  // brilliant code idea to test here
  return;
  // the rest of a dysfunctional sketch here
  // this code will never be executed
}
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Control structure
            > Dowhile

do...while
          [Control Structure]

Description
The do…while loop works in the same manner as the while loop, with the exception that the condition is tested at the end of the loop, so the do loop will always run at least once.
Syntax
do {
  // statement block


Syntax
do {
  // statement block
} while (condition);
Parameters
condition: a boolean expression that evaluates to true or false.
Example Code
int x = 0;
do {
  delay(50);          // wait for sensors to stabilize
  x = readSensors();  // check the sensors
} while (x < 100);
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Control structure
            > Continue

continue
          [Control Structure]

Description
The continue statement skips the rest of the current iteration of a loop (for, while, or do…while). It continues by checking the conditional expression of the loop, and proceeding with any subsequent iterations.
Example Code


Example Code
The following code writes the value of 0 to 255 to the PWMpin, but skips the values in the range of 41 to 119.
for (int x = 0; x <= 255; x ++) {
  if (x > 40 && x < 120) {  // create jump in values
    continue;
  }
  analogWrite(PWMpin, x);
  delay(50);
}
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Control structure
            > Switchcase

switch...case
          [Control Structure]

Description


switch...case
          [Control Structure]

Description
Like if statements, switch case controls the flow of programs by allowing programmers to specify different code that should be executed in various conditions. In particular, a switch statement compares the value of a variable to the values specified in case statements. When a case statement is found whose value matches that of the variable, the code in that case statement is run.
The break keyword exits the switch statement, and is typically used at the end of each case. Without a break statement, the switch statement will continue executing the following expressions ("falling-through") until a break, or the end of the switch statement is reached.
Syntax
switch (var) {
  case label1:
    // statements
    break;
  case label2:
    // statements
    break;
  default:
    // statements
    break;
}
Parameters


break;
  default:
    // statements
    break;
}
Parameters
var: a variable whose value to compare with various cases. Allowed data types: int, char.
label1, label2: constants. Allowed data types: int, char.
Returns
Nothing
Example Code
switch (var) {
  case 1:
    //do something when var equals 1
    break;
  case 2:
    //do something when var equals 2
    break;
  default:
    // if nothing else matches, do the default
    // default is optional
    break;
}
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Structure
            >  Control structure
            > While

while
          [Control Structure]

Description


> While

while
          [Control Structure]

Description
A while loop will loop continuously, and infinitely, until the expression inside the parenthesis, () becomes false. Something must change the tested variable, or the while loop will never exit. This could be in your code, such as an incremented variable, or an external condition, such as testing a sensor.
Syntax
while (condition) {
  // statement(s)
}
Parameters
condition: a boolean expression that evaluates to true or false.
Example Code
var = 0;
while (var < 200) {
  // do something repetitive 200 times
  var++;
}
See also
EXAMPLE While Loop


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Variable scope qualifiers
            > Volatile

volatile
          [Variable Scope & Qualifiers]

Description
volatile is a keyword known as a variable qualifier, it is usually used before the datatype of a variable, to modify the way in which the compiler and subsequent program treat the variable.


Declaring a variable volatile is a directive to the compiler. The compiler is software which translates your C/C++ code into the machine code, which are the real instructions for the Atmega chip in the Arduino.
Specifically, it directs the compiler to load the variable from RAM and not from a storage register, which is a temporary memory location where program variables are stored and manipulated. Under certain conditions, the value for a variable stored in registers can be inaccurate.
A variable should be declared volatile whenever its value can be changed by something beyond the control of the code section in which it appears, such as a concurrently executing thread. In the Arduino, the only place that this is likely to occur is in sections of code associated with interrupts, called an interrupt service routine.
int or long volatiles


int or long volatiles
If the volatile variable is bigger than a byte (e.g. a 16 bit int or a 32 bit long), then the microcontroller can not read it in one step, because it is an 8 bit microcontroller. This means that while your main code section (e.g. your loop) reads the first 8 bits of the variable, the interrupt might already change the second 8 bits. This will produce random values for the variable.
Remedy:
While the variable is read, interrupts need to be disabled, so they can’t mess with the bits, while they are read.
There are several ways to do this:
LANGUAGE noInterrupts
use the ATOMIC_BLOCK macro. Atomic operations are single MCU operations - the smallest possible unit.
Example Code


Example Code
The volatile modifier ensures that changes to the state variable are immediately visible in loop(). Without the volatile modifier, the state variable may be loaded into a register when entering the function and would not be updated anymore until the function ends.
// Flashes the LED for 1 s if the input has changed
// in the previous second.
volatile byte changed = 0;
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(2), toggle, CHANGE);
}
void loop() {
  if (changed == 1) {
    // toggle() has been called from interrupts!
    // Reset changed to 0
    changed = 0;
    // Blink LED for 200 ms
    digitalWrite(LED_BUILTIN, HIGH);
    delay(200);
    digitalWrite(LED_BUILTIN, LOW);
  }
}
void toggle() {


digitalWrite(LED_BUILTIN, LOW);
  }
}
void toggle() {
  changed = 1;
}
To access a variable with size greater than the microcontroller’s 8-bit data bus, use the ATOMIC_BLOCK macro. The macro ensures that the variable is read in an atomic operation, i.e. its contents cannot be altered while it is being read.
#include <util/atomic.h> // this library includes the ATOMIC_BLOCK macro.
volatile int input_from_interrupt;
// Somewhere in the code, e.g. inside loop()
  ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
    // code with interrupts blocked (consecutive atomic operations will not get interrupted)
    int result = input_from_interrupt;
  }
See also
LANGUAGE attachInterrupt


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Variable scope qualifiers
            > Const

const
          [Variable Scope & Qualifiers]

Description


const
          [Variable Scope & Qualifiers]

Description
The const keyword stands for constant. It is a variable qualifier that modifies the behavior of the variable, making a variable "read-only". This means that the variable can be used just as any other variable of its type, but its value cannot be changed. You will get a compiler error if you try to assign a value to a const variable.
Constants defined with the const keyword obey the rules of variable scoping that govern other variables. This, and the pitfalls of using #define, makes the const keyword a superior method for defining constants and is preferred over using #define.
Example Code
const float pi = 3.14;
float x;
// ....
x = pi * 2; // it's fine to use consts in math
pi = 7;     // illegal - you can't write to (modify) a constant
Notes and Warnings
#define or const


Notes and Warnings
#define or const
You can use either const or #define for creating numeric or string constants. For arrays, you will need to use const. In general const is preferred over #define for defining constants.
See also
LANGUAGE #define


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Variable scope qualifiers
            > Scope

scope
          [Variable Scope & Qualifiers]

Description
Variables in the C++ programming language, which Arduino uses, have a property called scope. This is in contrast to early versions of languages such as BASIC where every variable is a global variable.


A global variable is one that can be seen by every function in a program. Local variables are only visible to the function in which they are declared. In the Arduino environment, any variable declared outside of a function (e.g. setup(), loop(), etc. ), is a global variable.
When programs start to get larger and more complex, local variables are a useful way to insure that only one function has access to its own variables. This prevents programming errors when one function inadvertently modifies variables used by another function.
It is also sometimes handy to declare and initialize a variable inside a for loop. This creates a variable that can only be accessed from inside the for-loop brackets.
Example Code
int gPWMval;  // any function will see this variable
void setup() {
  // ...
}
void loop() {
  int i;    // "i" is only "visible" inside of "loop"


int i;    // "i" is only "visible" inside of "loop"
  float f;  // "f" is only "visible" inside of "loop"
  // ...
  for (int j = 0; j < 100; j++) {
    // variable j can only be accessed inside the for-loop brackets
  }
}
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Variable scope qualifiers
            > Static

static
          [Variable Scope & Qualifiers]

Description
The static keyword is used to create variables that are visible to only one function. However unlike local variables that get created and destroyed every time a function is called, static variables persist beyond the function call, preserving their data between function calls.


Variables declared as static will only be created and initialized the first time a function is called.
Example Code
/* RandomWalk
  Paul Badger 2007
  RandomWalk wanders up and down randomly between two
  endpoints. The maximum move in one loop is governed by
  the parameter "stepsize".
  A static variable is moved up and down a random amount.
  This technique is also known as "pink noise" and "drunken walk".
*/
#define randomWalkLowRange -20
#define randomWalkHighRange 20
int stepsize;
int thisTime;
void setup() {
  Serial.begin(9600);
}
void loop() {
  //  test randomWalk function
  stepsize = 5;
  thisTime = randomWalk(stepsize);
  Serial.println(thisTime);
  delay(10);
}
int randomWalk(int moveSize) {


delay(10);
}
int randomWalk(int moveSize) {
  static int place; // variable to store value in random walk - declared static so that it stores
  // values in between function calls, but no other functions can change its value
  place = place + (random(-moveSize, moveSize + 1));
  if (place < randomWalkLowRange) {                               // check lower and upper limits
    place = randomWalkLowRange + (randomWalkLowRange - place);    // reflect number back in positive direction
  }
  else if (place > randomWalkHighRange) {
    place = randomWalkHighRange - (place - randomWalkHighRange);  // reflect number back in negative direction
  }
  return place;
}
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Conversion
            > Bytecast

byte()
          [Conversion]

Description
Converts a value to the byte data type.
Syntax
byte(x)
(byte)x (C-style type conversion)
Parameters
x: a value. Allowed data types: any type.
Returns
Data type: byte.
See also
LANGUAGE byte


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Conversion
            > Wordcast

word()
          [Conversion]

Description
Converts a value to the word data type.
Syntax
word(x)
word(h, l)
(word)x (C-style type conversion)
Parameters
x: a value. Allowed data types: any type.


Parameters
x: a value. Allowed data types: any type.
h: the high-order (leftmost) byte of the word.
l: the low-order (rightmost) byte of the word.
Returns
Data type: word.
See also
LANGUAGE word


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Conversion
            > Intcast

int()
          [Conversion]

Description
Converts a value to the int data type.
Syntax
int(x)
(int)x (C-style type conversion)
Parameters
x: a value. Allowed data types: any type.
Returns
Data type: int.
See also
LANGUAGE int


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Conversion
            > Charcast

char()
          [Conversion]

Description
Converts a value to the char data type.
Syntax
char(x)
(char)x (C-style type conversion)
Parameters
x: a value. Allowed data types: any type.
Returns
Data type: char.
See also
LANGUAGE char


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Conversion
            > Unsignedlongcast

(unsigned long)
          [Conversion]

Description
Converts a value to the unsigned long data type.
Syntax
(unsigned long)x
Parameters
x: a value of any type
Returns
unsigned long
See also
LANGUAGE unsigned long


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Conversion
            > Floatcast

float()
          [Conversion]

Description
Converts a value to the float data type.
Syntax
float(x)
(float)x (C-style type conversion)
Parameters
x: a value. Allowed data types: any type.
Returns
Data type: float.
Notes and Warnings


Returns
Data type: float.
Notes and Warnings
See the reference for float for details about the precision and limitations of floating point numbers on Arduino.
See also
LANGUAGE float


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Conversion
            > Longcast

long()
          [Conversion]

Description
Converts a value to the long data type.
Syntax
long(x)
(long)x (C-style type conversion)
Parameters
x: a value. Allowed data types: any type.
Returns
Data type: long.
See also
LANGUAGE long


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Conversion
            > Unsignedintcast

(unsigned int)
          [Conversion]

Description
Converts a value to the unsigned int data type.
Syntax
(unsigned int)x
Parameters
x: a value of any type
Returns
unsigned int
See also
LANGUAGE unsigned int


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > String

string
          [Data Types]

Description


> String

string
          [Data Types]

Description
Text strings can be represented in two ways. you can use the String data type, which is part of the core as of version 0019, or you can make a string out of an array of type char and null-terminate it. This page described the latter method. For more details on the String object, which gives you more functionality at the cost of more memory, see the String object page.
Syntax
All of the following are valid declarations for strings.
char Str1[15];
char Str2[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o'};
char Str3[8] = {'a', 'r', 'd', 'u', 'i', 'n', 'o', '\0'};
char Str4[] = "arduino";


char Str4[] = "arduino";
char Str5[8] = "arduino";
char Str6[15] = "arduino";
Possibilities for declaring strings
Declare an array of chars without initializing it as in Str1
Declare an array of chars (with one extra char) and the compiler will add the required null character, as in Str2
Explicitly add the null character, Str3
Initialize with a string constant in quotation marks; the compiler will size the array to fit the string constant and a terminating null character, Str4
Initialize the array with an explicit size and string constant, Str5
Initialize the array, leaving extra space for a larger string, Str6
Null termination
Generally, strings are terminated with a null character (ASCII code 0). This allows functions (like Serial.print()) to tell where the end of a string is. Otherwise, they would continue reading subsequent bytes of memory that aren’t actually part of the string.


This means that your string needs to have space for one more character than the text you want it to contain. That is why Str2 and Str5 need to be eight characters, even though "arduino" is only seven - the last position is automatically filled with a null character. Str4 will be automatically sized to eight characters, one for the extra null. In Str3, we’ve explicitly included the null character (written '\0') ourselves.
Note that it’s possible to have a string without a final null character (e.g. if you had specified the length of Str2 as seven instead of eight). This will break most functions that use strings, so you shouldn’t do it intentionally. If you notice something behaving strangely (operating on characters not in the string), however, this could be the problem.
Single quotes or double quotes?
Strings are always defined inside double quotes ("Abc") and characters are always defined inside single quotes('A').


Wrapping long strings
You can wrap long strings like this:
char myString[] = "This is the first line"
" this is the second line"
" etcetera";
Arrays of strings
It is often convenient, when working with large amounts of text, such as a project with an LCD display, to setup an array of strings. Because strings themselves are arrays, this is actually an example of a two-dimensional array.
In the code below, the asterisk after the datatype char “char*” indicates that this is an array of “pointers”. All array names are actually pointers, so this is required to make an array of arrays. Pointers are one of the more esoteric parts of C++ for beginners to understand, but it isn’t necessary to understand pointers in detail to use them effectively here.
Example Code


Example Code
char *myStrings[] = {"This is string 1", "This is string 2", "This is string 3",
                     "This is string 4", "This is string 5", "This is string 6"
                    };
void setup() {
  Serial.begin(9600);
}
void loop() {
  for (int i = 0; i < 6; i++) {
    Serial.println(myStrings[i]);
    delay(500);
  }
}
See also
LANGUAGE PROGMEM


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Void

void
          [Data Types]

Description
The void keyword is used only in function declarations. It indicates that the function is expected to return no information to the function from which it was called.
Example Code
The code shows how to use void.
// actions are performed in the functions "setup" and "loop"


// actions are performed in the functions "setup" and "loop"
// but  no information is reported to the larger program
void setup() {
  // ...
}
void loop() {
  // ...
}
See also
LANGUAGE Integer Constants


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Int

int
          [Data Types]

Description
Integers are your primary data-type for number storage.


Description
Integers are your primary data-type for number storage.
On the Arduino Uno (and other ATmega based boards) an int stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1).
On the Arduino Due and SAMD based boards (like MKR1000 and Zero), an int stores a 32-bit (4-byte) value. This yields a range of -2,147,483,648 to 2,147,483,647 (minimum value of -2^31 and a maximum value of (2^31) - 1).


int’s store negative numbers with a technique called (2’s complement math). The highest bit, sometimes referred to as the "sign" bit, flags the number as a negative number. The rest of the bits are inverted and 1 is added.
The Arduino takes care of dealing with negative numbers for you, so that arithmetic operations work transparently in the expected manner. There can be an unexpected complication in dealing with the bitshift right operator (>>) however.
Syntax
int var = val;
Parameters
var: variable name.
val: the value you assign to that variable.
Example Code
This code creates an integer called 'countUp', which is initially set as the number 0 (zero). The variable goes up by 1 (one) each loop, being displayed on the serial monitor.
int countUp = 0;            //creates a variable integer called 'countUp'
void setup() {


void setup() {
  Serial.begin(9600);       // use the serial port to print the number
}
void loop() {
  countUp++;                //Adds 1 to the countUp int on every loop
  Serial.println(countUp);  // prints out the current state of countUp
  delay(1000);
}
Notes and Warnings
When signed variables are made to exceed their maximum or minimum capacity they overflow. The result of an overflow is unpredictable so this should be avoided. A typical symptom of an overflow is the variable "rolling over" from its maximum capacity to its minimum or vice versa, but this is not always the case. If you want this behavior, use unsigned int.
See also
LANGUAGE Integer Constants


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Word

word
          [Data Types]

Description
A word can store an unsigned number of at least 16 bits (from 0 to 65535).
Syntax
word var = val;
Parameters
var: variable name.
val: the value to assign to that variable.
Example Code


var: variable name.
val: the value to assign to that variable.
Example Code
word w = 10000;
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Float

float
          [Data Types]

Description


> Float

float
          [Data Types]

Description
Datatype for floating-point numbers, a number that has a decimal point. Floating-point numbers are often used to approximate analog and continuous values because they have greater resolution than integers. Floating-point numbers can be as large as 3.4028235E+38 and as low as -3.4028235E+38. They are stored as 32 bits (4 bytes) of information.
Syntax
float var = val;
Parameters
var: variable name.
val: the value you assign to that variable.
Example Code
float myfloat;
float sensorCalbrate = 1.117;
int x;
int y;
float z;
x = 1;
y = x / 2;          // y now contains 0, ints can't hold fractions


z = (float)x / 2.0; // z now contains .5 (you have to use 2.0, not 2)
Notes and Warnings
If doing math with floats, you need to add a decimal point, otherwise it will be treated as an int. See the Floating point constants page for details.
The float data type has only 6-7 decimal digits of precision. That means the total number of digits, not the number to the right of the decimal point. Unlike other platforms, where you can get more precision by using a double (e.g. up to 15 digits), on the Arduino, double is the same size as float.
Floating point numbers are not exact, and may yield strange results when compared. For example 9.0 / 0.3 may not quite equal 30.0. You should instead check that the absolute value of the difference between the numbers is less than some small number.


Conversion from floating point to integer math results in truncation:
float x = 2.9; // A float type variable
int y = x;  // 2
If, instead, you want to round off during the conversion process, you need to add 0.5:
float x = 2.9;
int y = x + 0.5;  // 3
or use the round() function:
float x = 2.9;
int y = round(x);  // 3
Floating point math is also much slower than integer math in performing calculations, so should be avoided if, for example, a loop has to run at top speed for a critical timing function. Programmers often go to some lengths to convert floating point calculations to integer math to increase speed.
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Long

long
          [Data Types]

Description
Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from -2,147,483,648 to 2,147,483,647.


If doing math with integers at least one of the values must be of type long, either an integer constant followed by an L or a variable of type long, forcing it to be a long. See the Integer Constants page for details.
Syntax
long var = val;
Parameters
var: variable name.
val: the value assigned to the variable.
Example Code
long speedOfLight_km_s = 300000L;  // see the Integer Constants page for explanation of the 'L'
See also
LANGUAGE Integer Constants


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Boolean

boolean
          [Data Types]

Description
boolean is a non-standard type alias for bool defined by Arduino. It’s recommended to instead use the standard type bool, which is identical.
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Bool

bool
          [Data Types]

Description
A bool holds one of two values, true or false. (Each bool variable occupies one byte of memory.)
Syntax
bool var = val;
Parameters
var: variable name.
val: the value to assign to that variable.
Example Code


var: variable name.
val: the value to assign to that variable.
Example Code
This code shows how to use the bool datatype.
int LEDpin = 5;     // LED on pin 5
int switchPin = 13; // momentary switch on 13, other side connected to ground
bool running = false;
void setup() {
  pinMode(LEDpin, OUTPUT);
  pinMode(switchPin, INPUT);
  digitalWrite(switchPin, HIGH);  // turn on pullup resistor
}
void loop() {
  if (digitalRead(switchPin) == LOW) {
    // switch is pressed - pullup keeps pin high normally
    delay(100);                     // delay to debounce switch
    running = !running;             // toggle running variable
    digitalWrite(LEDpin, running);  // indicate via LED
  }
}
See also
LANGUAGE constants


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Stringobject

String()
          [Data Types]

Description
Constructs an instance of the String class. There are multiple versions that construct Strings from different data types (i.e. format them as sequences of characters), including:
a constant string of characters, in double quotes (i.e. a char array)


a constant string of characters, in double quotes (i.e. a char array)
a single constant character, in single quotes
another instance of the String object
a constant integer or long integer
a constant integer or long integer, using a specified base
an integer or long integer variable
an integer or long integer variable, using a specified base
a float or double, using a specified decimal places
Constructing a String from a number results in a string that contains the ASCII representation of that number. The default is base ten, so
String thisString = String(13);
gives you the String "13". You can use other bases, however. For example,
String thisString = String(13, HEX);
gives you the String "d", which is the hexadecimal representation of the decimal value 13. Or if you prefer binary,
String thisString = String(13, BIN);


String thisString = String(13, BIN);
gives you the String "1101", which is the binary representation of 13.
Syntax
String(val)
String(val, base)
String(val, decimalPlaces)
Parameters
val:  a variable to format as a String. Allowed data types: string, char, byte, int, long, unsigned int, unsigned long, float, double.
base: (optional) the base in which to format an integral value.
decimalPlaces: only if val is float or double. The desired decimal places.
Returns
An instance of the String class.
Example Code
All of the following are valid declarations for Strings.
String stringOne = "Hello String";                    // using a constant String
String stringOne = String('a');                       // converting a constant char into a String
String stringTwo = String("This is a string");        // converting a constant string into a String object


String stringOne = String(stringTwo + " with more");  // concatenating two strings
String stringOne = String(13);                        // using a constant integer
String stringOne = String(analogRead(0), DEC);        // using an int and a base
String stringOne = String(45, HEX);                   // using an int and a base (hexadecimal)
String stringOne = String(255, BIN);                  // using an int and a base (binary)
String stringOne = String(millis(), DEC);             // using a long and a base
String stringOne = String(5.698, 3);                  // using a float and the decimal places
Functions
LANGUAGE charAt()
LANGUAGE compareTo()
LANGUAGE concat()
LANGUAGE c_str()
LANGUAGE endsWith()
LANGUAGE equals()
LANGUAGE equalsIgnoreCase()
LANGUAGE getBytes()
LANGUAGE indexOf()
LANGUAGE lastIndexOf()
LANGUAGE length()
LANGUAGE remove()


LANGUAGE indexOf()
LANGUAGE lastIndexOf()
LANGUAGE length()
LANGUAGE remove()
LANGUAGE replace()
LANGUAGE reserve()
LANGUAGE setCharAt()
LANGUAGE startsWith()
LANGUAGE substring()
LANGUAGE toCharArray()
LANGUAGE toDouble()
LANGUAGE toInt()
LANGUAGE toFloat()
LANGUAGE toLowerCase()
LANGUAGE toUpperCase()
LANGUAGE trim()
Operators
LANGUAGE [] (element access)
LANGUAGE + (concatenation)
LANGUAGE += (append)
LANGUAGE == (comparison)
LANGUAGE > (greater than)
LANGUAGE >= (greater than or equal to)
LANGUAGE < (less than)
LANGUAGE <= (less than or equal to)
LANGUAGE != (different from)
EXAMPLE String Tutorials
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Size t

size_t
          [Data Types]

Description
size_t is a data type capable of representing the size of any object in bytes. Examples of the use of size_t are the return type of sizeof() and Serial.print().
Syntax
size_t var = val;
Parameters
var: variable name.


Syntax
size_t var = val;
Parameters
var: variable name.
val: the value to assign to that variable.
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Short

short
          [Data Types]

Description
A short is a 16-bit data-type.


Description
A short is a 16-bit data-type.
On all Arduinos (ATMega and ARM based) a short stores a 16-bit (2-byte) value. This yields a range of -32,768 to 32,767 (minimum value of -2^15 and a maximum value of (2^15) - 1).
Syntax
short var = val;
Parameters
var: variable name.
val: the value you assign to that variable.
Example Code
short ledPin = 13
See also
LANGUAGE Integer Constants


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Double

double
          [Data Types]

Description
Double precision floating point number. On the Uno and other ATMEGA based boards, this occupies 4 bytes. That is, the double implementation is exactly the same as the float, with no gain in precision.


On the Arduino Due, doubles have 8-byte (64 bit) precision.
Syntax
double var = val;
Parameters
var: variable name.
val: the value to assign to that variable.
Notes and Warnings
Users who borrow code from other sources that includes double variables may wish to examine the code to see if the implied precision is different from that actually achieved on ATMEGA based Arduinos.
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Unsignedchar

unsigned char
          [Data Types]

Description
An unsigned data type that occupies 1 byte of memory. Same as the byte datatype.
The unsigned char datatype encodes numbers from 0 to 255.
For consistency of Arduino programming style, the byte data type is to be preferred.
Syntax


For consistency of Arduino programming style, the byte data type is to be preferred.
Syntax
unsigned char var = val;
Parameters
var: variable name.
val: the value to assign to that variable.
Example Code
unsigned char myChar = 240;
See also
LANGUAGE Serial.println


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Unsignedint

unsigned int
          [Data Types]

Description


> Unsignedint

unsigned int
          [Data Types]

Description
On the Uno and other ATMEGA based boards, unsigned ints (unsigned integers) are the same as ints in that they store a 2 byte value. Instead of storing negative numbers however they only store positive values, yielding a useful range of 0 to 65,535 ((2^16) - 1).
The Due stores a 4 byte (32-bit) value, ranging from 0 to 4,294,967,295 (2^32 - 1).
The difference between unsigned ints and (signed) ints, lies in the way the highest bit, sometimes referred to as the "sign" bit, is interpreted. In the Arduino int type (which is signed), if the high bit is a "1", the number is interpreted as a negative number, and the other 15 bits are interpreted with (2’s complement math).
Syntax


Syntax
unsigned int var = val;
Parameters
var: variable name.
val: the value you assign to that variable.
Example Code
unsigned int ledPin = 13;
Notes and Warnings
When unsigned variables are made to exceed their maximum capacity they "roll over" back to 0, and also the other way around:
unsigned int x;
x = 0;
x = x - 1;  // x now contains 65535 - rolls over in neg direction
x = x + 1;  // x now contains 0 - rolls over
Math with unsigned variables may produce unexpected results, even if your unsigned variable never rolls over.
The MCU applies the following rules:
The calculation is done in the scope of the destination variable. E.g. if the destination variable is signed, it will do signed math, even if both input variables are unsigned.


However with a calculation which requires an intermediate result, the scope of the intermediate result is unspecified by the code. In this case, the MCU will do unsigned math for the intermediate result, because both inputs are unsigned!
unsigned int x = 5;
unsigned int y = 10;
int result;
result = x - y; // 5 - 10 = -5, as expected
result = (x - y) / 2; // 5 - 10 in unsigned math is 65530!  65530/2 = 32765
// solution: use signed variables, or do the calculation step by step.
result = x - y; // 5 - 10 = -5, as expected
result = result / 2;  //  -5/2 = -2 (only integer math, decimal places are dropped)
Why use unsigned variables at all?


Why use unsigned variables at all?
The rollover behaviour is desired, e.g. counters
The signed variable is a bit too small, but you want to avoid the memory and speed loss of long/float.
See also
LANGUAGE Integer Constants


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Char

char
          [Data Types]

Description
A data type used to store a character value. Character literals are written in single quotes, like this: 'A' (for multiple characters - strings - use double quotes: "ABC").


Characters are stored as numbers however. You can see the specific encoding in the ASCII chart. This means that it is possible to do arithmetic on characters, in which the ASCII value of the character is used (e.g. 'A' + 1 has the value 66, since the ASCII value of the capital letter A is 65). See Serial.println reference for more on how characters are translated to numbers.
The size of the char datatype is at least 8 bits. It’s recommended to only use char for storing characters. For an unsigned, one-byte (8 bit) data type, use the byte data type.
Syntax
char var = val;
Parameters
var: variable name.
val: the value to assign to that variable.
Example Code
char myChar = 'A';
char myChar = 65; // both are equivalent
See also
LANGUAGE Serial.println


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Byte

byte
          [Data Types]

Description
A byte stores an 8-bit unsigned number, from 0 to 255.
Syntax
byte var = val;
Parameters
var: variable name.
val: the value to assign to that variable.
See also
LANGUAGE byte()


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Array

array
          [Data Types]

Description
An array is a collection of variables that are accessed with an index number. Arrays in the C++ programming language Arduino sketches are written in can be complicated, but using simple arrays is relatively straightforward.
Creating (Declaring) an Array


Creating (Declaring) an Array
All of the methods below are valid ways to create (declare) an array.
  int myInts[6];
  int myPins[] = {2, 4, 8, 3, 6};
  int mySensVals[5] = {2, 4, -8, 3, 2};
  char message[6] = "hello";
You can declare an array without initializing it as in myInts.
In myPins we declare an array without explicitly choosing a size. The compiler counts the elements and creates an array of the appropriate size.
Finally you can both initialize and size your array, as in mySensVals. Note that when declaring an array of type char, one more element than your initialization is required, to hold the required null character.
Accessing an Array


Accessing an Array
Arrays are zero indexed, that is, referring to the array initialization above, the first element of the array is at index 0, hence
mySensVals[0] == 2, mySensVals[1] == 4, and so forth.
It also means that in an array with ten elements, index nine is the last element. Hence:
int myArray[10]={9, 3, 2, 4, 3, 2, 7, 8, 9, 11};
// myArray[9]    contains 11
// myArray[10]   is invalid and contains random information (other memory address)


// myArray[10]   is invalid and contains random information (other memory address)
For this reason you should be careful in accessing arrays. Accessing past the end of an array (using an index number greater than your declared array size - 1) is reading from memory that is in use for other purposes. Reading from these locations is probably not going to do much except yield invalid data. Writing to random memory locations is definitely a bad idea and can often lead to unhappy results such as crashes or program malfunction. This can also be a difficult bug to track down.
Unlike BASIC or JAVA, the C++ compiler does no checking to see if array access is within legal bounds of the array size that you have declared.
To assign a value to an array:
mySensVals[0] = 10;
To retrieve a value from an array:
x = mySensVals[4];
Arrays and FOR Loops


x = mySensVals[4];
Arrays and FOR Loops
Arrays are often manipulated inside for loops, where the loop counter is used as the index for each array element. For example, to print the elements of an array over the serial port, you could do something like this:
for (byte i = 0; i < 5; i = i + 1) {
  Serial.println(myPins[i]);
}
Example Code
For a complete program that demonstrates the use of arrays, see the (How to Use Arrays example) from the (Built-in Examples).
See also
LANGUAGE PROGMEM


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Data types
            > Unsignedlong

unsigned long
          [Data Types]

Description


> Unsignedlong

unsigned long
          [Data Types]

Description
Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won’t store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).
Syntax
unsigned long var = val;
Parameters
var: variable name.
val: the value you assign to that variable.
Example Code
unsigned long time;
void setup() {
  Serial.begin(9600);
}
void loop() {
  Serial.print("Time: ");
  time = millis();
  //prints time since program started
  Serial.println(time);
  // wait a second so as not to send massive amounts of data
  delay(1000);
}
See also
LANGUAGE Integer Constants


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Utilities
            > Progmem

PROGMEM
          [Utilities]

Description
Store data in flash (program) memory instead of SRAM. There’s a description of the various types of memory available on an Arduino board.


The PROGMEM keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "put this information into flash memory", instead of into SRAM, where it would normally go.
PROGMEM is part of the pgmspace.h library. It is included automatically in modern versions of the IDE. However, if you are using an IDE version below 1.0 (2011), you’ll first need to include the library at the top of your sketch, like this:
#include <avr/pgmspace.h>
While PROGMEM could be used on a single variable, it is really only worth the fuss if you have a larger block of data that needs to be stored, which is usually easiest in an array, (or another C++ data structure beyond our present discussion).


Using PROGMEM is also a two-step procedure. After getting the data into Flash memory, it requires special methods (functions), also defined in the pgmspace.h library, to read the data from program memory back into SRAM, so we can do something useful with it.
Syntax
const dataType variableName[] PROGMEM = {data0, data1, data3…};
Note that because PROGMEM is a variable modifier, there is no hard and fast rule about where it should go, so the Arduino compiler accepts all of the definitions below, which are also synonymous. However, experiments have indicated that, in various versions of Arduino (having to do with GCC version), PROGMEM may work in one location and not in another. The "string table" example below has been tested to work with Arduino 13. Earlier versions of the IDE may work better if PROGMEM is included after the variable name.
const dataType variableName[] PROGMEM = {};  // use this form


const dataType variableName[] PROGMEM = {};  // use this form
const PROGMEM dataType variableName[] = {};  // or this one
const dataType PROGMEM variableName[] = {};  // not this one
Parameters
dataType: Allowed data types: any variable type.
variableName: the name for your array of data.
Example Code
The following code fragments illustrate how to read and write unsigned chars (bytes) and ints (2 bytes) to PROGMEM.
// save some unsigned ints
const PROGMEM uint16_t charSet[] = { 65000, 32796, 16843, 10, 11234};
// save some chars
const char signMessage[] PROGMEM = {"I AM PREDATOR,  UNSEEN COMBATANT. CREATED BY THE UNITED STATES DEPART"};
unsigned int displayInt;
char myChar;
void setup() {
  Serial.begin(9600);


char myChar;
void setup() {
  Serial.begin(9600);
  while (!Serial);  // wait for serial port to connect. Needed for native USB
  // put your setup code here, to run once:
  // read back a 2-byte int
  for (byte k = 0; k < 5; k++) {
    displayInt = pgm_read_word_near(charSet + k);
    Serial.println(displayInt);
  }
  Serial.println();
  // read back a char
  for (byte k = 0; k < strlen_P(signMessage); k++) {
    myChar = pgm_read_byte_near(signMessage + k);
    Serial.print(myChar);
  }
  Serial.println();
}
void loop() {
  // put your main code here, to run repeatedly:
}
Arrays of strings


// put your main code here, to run repeatedly:
}
Arrays of strings
It is often convenient when working with large amounts of text, such as a project with an LCD, to setup an array of strings. Because strings themselves are arrays, this is actually an example of a two-dimensional array.
These tend to be large structures so putting them into program memory is often desirable. The code below illustrates the idea.
/*
  PROGMEM string demo
  How to store a table of strings in program memory (flash),
  and retrieve them.
  Information summarized from:
  http://www.nongnu.org/avr-libc/user-manual/pgmspace.html
  Setting up a table (array) of strings in program memory is slightly complicated, but
  here is a good template to follow.
  Setting up the strings is a two-step process. First, define the strings.
*/
#include <avr/pgmspace.h>


*/
#include <avr/pgmspace.h>
const char string_0[] PROGMEM = "String 0"; // "String 0" etc are strings to store - change to suit.
const char string_1[] PROGMEM = "String 1";
const char string_2[] PROGMEM = "String 2";
const char string_3[] PROGMEM = "String 3";
const char string_4[] PROGMEM = "String 4";
const char string_5[] PROGMEM = "String 5";
// Then set up a table to refer to your strings.
const char *const string_table[] PROGMEM = {string_0, string_1, string_2, string_3, string_4, string_5};
char buffer[30];  // make sure this is large enough for the largest string it must hold
void setup() {
  Serial.begin(9600);


void setup() {
  Serial.begin(9600);
  while (!Serial);  // wait for serial port to connect. Needed for native USB
  Serial.println("OK");
}
void loop() {
  /* Using the string table in program memory requires the use of special functions to retrieve the data.
     The strcpy_P function copies a string from program space to a string in RAM ("buffer").
     Make sure your receiving string in RAM is large enough to hold whatever
     you are retrieving from program space. */
  for (int i = 0; i < 6; i++) {
    strcpy_P(buffer, (char *)pgm_read_word(&(string_table[i])));  // Necessary casts and dereferencing, just copy.
    Serial.println(buffer);
    delay(500);
  }
}
Notes and Warnings


delay(500);
  }
}
Notes and Warnings
Please note that variables must be either globally defined, OR defined with the static keyword, in order to work with PROGMEM.
The following code will NOT work when inside a function:
const char long_str[] PROGMEM = "Hi, I would like to tell you a bit about myself.\n";
The following code WILL work, even if locally defined within a function:
const static char long_str[] PROGMEM = "Hi, I would like to tell you a bit about myself.\n"
The F() macro
When an instruction like :
Serial.print("Write something on  the Serial Monitor");
is used, the string to be printed is normally saved in RAM. If your sketch prints a lot of stuff on the Serial Monitor, you can easily fill the RAM. If you have free FLASH memory space, you can easily indicate that the string must be saved in FLASH using the syntax:


Serial.print(F("Write something on the Serial Monitor that is stored in FLASH"));
See also
EXAMPLE Types of memory available on an Arduino board
DEFINITION array
DEFINITION string


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Utilities
            > Sizeof

sizeof()
          [Utilities]

Description
The sizeof operator returns the number of bytes in a variable type, or the number of bytes occupied by an array.
Syntax
sizeof(variable)
Parameters


Syntax
sizeof(variable)
Parameters
variable: The thing to get the size of. Allowed data types: any variable type or array (e.g. int, float, byte).
Returns
The number of bytes in a variable or bytes occupied in an array. Data type: size_t.
Example Code
The sizeof operator is useful for dealing with arrays (such as strings) where it is convenient to be able to change the size of the array without breaking other parts of the program.
This program prints out a text string one character at a time. Try changing the text phrase.
char myStr[] = "this is a test";
void setup() {
  Serial.begin(9600);
}
void loop() {
  for (byte i = 0; i < sizeof(myStr) - 1; i++) {
    Serial.print(i, DEC);
    Serial.print(" = ");
    Serial.write(myStr[i]);


Serial.print(" = ");
    Serial.write(myStr[i]);
    Serial.println();
  }
  delay(5000);  // slow down the program
}
Notes and Warnings
Note that sizeof returns the total number of bytes. So for arrays of larger variable types such as ints, the for loop would look something like this.
int myValues[] = {123, 456, 789};
// this for loop works correctly with an array of any type or size
for (byte i = 0; i < (sizeof(myValues) / sizeof(myValues[0])); i++) {
  // do something with myValues[i]
}
Note that a properly formatted string ends with the NULL symbol, which has ASCII value 0.
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Constants
            > Integerconstants

Integer Constants
          [Constants]

Description
Integer constants are numbers that are used directly in a sketch, like 123. By default, these numbers are treated as int but you can change this with the U and L modifiers (see below).


Normally, integer constants are treated as base 10 (decimal) integers, but special notation (formatters) may be used to enter numbers in other bases.
Base
Example
Formatter
Comment
10 (decimal)
123
none
2 (binary)
0b1111011
leading "0b"
characters 0&1 valid
8 (octal)
0173
leading "0"
characters 0-7 valid
16 (hexadecimal)
0x7B
leading "0x"
characters 0-9, A-F, a-f valid
Decimal (base 10)
This is the common-sense math with which you are acquainted. Constants without other prefixes are assumed to be in decimal format.
Example  Code:
n = 101;  // same as 101 decimal ((1 * 10^2) + (0 * 10^1) + 1)


Binary (base 2)
Only the characters 0 and 1 are valid.
Example  Code:
n = 0b101; // same as 5 decimal ((1 * 2^2) + (0 * 2^1) + 1)
Octal (base 8)
Only the characters 0 through 7 are valid. Octal values are indicated by the prefix "0" (zero).
Example  Code:
n = 0101; // same as 65 decimal ((1 * 8^2) + (0 * 8^1) + 1)
It is possible to generate a hard-to-find bug by (unintentionally) including a leading zero before a constant and having the compiler unintentionally interpret your constant as octal.
Hexadecimal (base 16)


Hexadecimal (base 16)
Valid characters are 0 through 9 and letters A through F; A has the value 10, B is 11, up to F, which is 15. Hex values are indicated by the prefix "0x". Note that A-F may be upper (A-F) or lower case (a-f).
Example  Code:
n = 0x101;  // same as 257 decimal ((1 * 16^2) + (0 * 16^1) + 1)
Notes and Warnings
U & L formatters:
By default, an integer constant is treated as an int with the attendant limitations in values. To specify an integer constant with another data type, follow it with:
a 'u' or 'U' to force the constant into an unsigned data format. Example: 33u


a 'l' or 'L' to force the constant into a long data format. Example: 100000L
a 'ul' or 'UL' to force the constant into an unsigned long constant. Example: 32767ul
See also


Language
functions
variables
structure
Libraries
IoT Cloud API
Glossary
        The Arduino Reference text is licensed under a Creative Commons Attribution-Share Alike 3.0 License.

    Find anything that can be improved? Suggest corrections and new documentation via GitHub.
    Doubts on how to use Github? Learn everything you need to know in this tutorial.

Last Revision: Searching...
Last Build: 2023/06/30
Edit This Page
Reference
            >  Language
            >  Variables
            >  Constants
            > Constants

constants
          [Constants]

Description
Constants are predefined expressions in the Arduino language. They are used to make the programs easier to read. We classify constants in groups:
Defining Logical Levels: true and false (Boolean Constants)


Defining Logical Levels: true and false (Boolean Constants)
There are two constants used to represent truth and falsity in the Arduino language: true, and false.
false
false is the easier of the two to define. false is defined as 0 (zero).
true
true is often said to be defined as 1, which is correct, but true has a wider definition. Any integer which is non-zero is true, in a Boolean sense. So -1, 2 and -200 are all defined as true, too, in a Boolean sense.
Note that the true and false constants are typed in lowercase unlike HIGH, LOW, INPUT, and OUTPUT.
Defining Pin Levels: HIGH and LOW
When reading or writing to a digital pin there are only two possible values a pin can take/be-set-to: HIGH and LOW.
HIGH


HIGH
The meaning of HIGH (in reference to a pin) is somewhat different depending on whether a pin is set to an INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (ATmega) will report HIGH if:
a voltage greater than 3.0V is present at the pin (5V boards)
a voltage greater than 2.0V is present at the pin (3.3V boards)
A pin may also be configured as an INPUT with pinMode(), and subsequently made HIGH with digitalWrite(). This will enable the internal 20K pullup resistors, which will pull up the input pin to a HIGH reading unless it is pulled LOW by external circuitry. This can be done alternatively by passing INPUT_PULLUP as argument to the pinMode() function, as explained in more detail in the section "Defining Digital Pins modes: INPUT, INPUT_PULLUP, and OUTPUT" further below.


When a pin is configured to OUTPUT with pinMode(), and set to HIGH with digitalWrite(), the pin is at:
5 volts (5V boards)
3.3 volts (3.3V boards)
In this state it can source current, e.g. light an LED that is connected through a series resistor to ground.
LOW
The meaning of LOW also has a different meaning depending on whether a pin is set to INPUT or OUTPUT. When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (ATmega) will report LOW if:
a voltage less than 1.5V is present at the pin (5V boards)
a voltage less than 1.0V (Approx) is present at the pin (3.3V boards)


When a pin is configured to OUTPUT with pinMode(), and set to LOW with digitalWrite(), the pin is at 0 volts (both 5V and 3.3V boards). In this state it can sink current, e.g. light an LED that is connected through a series resistor to +5 volts (or +3.3 volts).
Defining Digital Pins modes: INPUT, INPUT_PULLUP, and OUTPUT
Digital pins can be used as INPUT, INPUT_PULLUP, or OUTPUT. Changing a pin with pinMode() changes the electrical behavior of the pin.
Pins Configured as INPUT
Arduino (ATmega) pins configured as INPUT with pinMode() are said to be in a high-impedance state. Pins configured as INPUT make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 Megohms in front of the pin. This makes them useful for reading a sensor.