Language Reference Flashcards
setup()
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
int buttonPin = 3; void setup() { Serial.begin(9600); pinMode(buttonPin, INPUT); } void loop() { // ... }
loop()
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
const 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); }
if
if (conditional) and ==, !=, <, > (comparison operators)
if
, which is used in conjunction with a comparison operator, tests whether a certain condition has been reached, such as an input being above a certain number. The format for an if test is:
if (someVariable \> 50) { // do something here }
The program tests to see if someVariable is greater than 50. If it is, the program takes a particular action. Put another way, if the statement in parentheses is true, the statements inside the brackets are run. If not, the program skips over the 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
The statements being evaluated inside the parentheses require the use of one or more operators:
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 greater than y) x \<= y (x is less than or equal to y) x \>= y (x is greater than or equal to y)
Warning:
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.
if can also be part of a branching control structure using the if…else] construction.
if/else
if/else allows greater control over the flow of code than the basic if statement, by allowing multiple tests to be grouped together. For example, an analog input could be tested and one action taken if the input was less than 500, and another action taken if the input was 500 or greater. The code would look like this:
if (pinFiveInput \< 500) { // action A } else { // action B }
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 is allowed.
if (pinFiveInput \< 500) { // do Thing A } else if (pinFiveInput \>= 1000) { // do Thing B } else { // do Thing C }
Another way to express branching, mutually exclusive tests, is with the switch case statement.
for
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.
There are three parts to the for loop header:
for (initialization; condition; increment) {
//statement(s);
}
The initialization happens first and exactly once. Each time through the loop, the 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.
Example
// 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); } }
Coding Tips
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() { 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); } }
switch case
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.
Example
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; }
Syntax
switch (var) { case label: // statements break; case label: // statements break; default: // statements break; }
Parameters
var: the variable whose value to compare to the various cases
label: a value to compare the variable to
while
while loops 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(expression){ // statement(s) }
Parameters
expression - a (boolean) C statement that evaluates to true or false
Example
var = 0; while(var \< 200){ // do something repetitive 200 times var++; }
do
The do 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.
do { // statement block } while (test condition);
Example
do { delay(50); // wait for sensors to stabilize x = readSensors(); // check the sensors } while (x \< 100);
break
break is used to exit from a do, for, or while loop, bypassing the normal loop condition. It is also used to exit from aswitch statement.
Example
for (x = 0; x < 255; x ++)
{
analogWrite(PWMpin, x);
sens = analogRead(sensorPin);
if (sens > threshold){ // bail out on sensor detect
x = 0;
break;
}
delay(50);
}
continue
The continue statement skips the rest of the current iteration of a loop (do, for, or while). It continues by checking the conditional expression of the loop, and proceeding with any subsequent iterations.
Example
for (x = 0; x < 255; x ++)
{
if (x > 40 && x < 120){ // create jump in values
continue;
}
analogWrite(PWMpin, x);
delay(50);
}
return
Terminate a function and return a value from a function to the calling function, if desired.
Syntax:
return;
return value; // both forms are valid
Parameters
value: any variable or constant type
Examples:
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 }
goto
Transfers program flow to a labeled point in the program
Syntax
label:
goto label; // sends program flow to the label
Tip
The use of goto is discouraged in C programming, and some authors of C programming books claim that the gotostatement 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.
Example
for(byte r = 0; r \< 255; r++){ for(byte g = 255; g \> -1; g--){ for(byte b = 0; b \< 255; b++){ if (analogRead(0) \> 250){ goto bailout;} // more statements ... } } } bailout:
; (semicolon)
; semicolon
Used to end a statement.
Example
int a = 13;
Tip
Forgetting to end a line in a semicolon will result in a compiler error. The error text may be obvious, and refer to a missing semicolon, or it may not. If an impenetrable or seemingly illogical compiler error comes up, one of the first things to check is a missing semicolon, in the immediate vicinity, preceding the line at which the compiler complained.
{ } (Curly Braces)
{} Curly Braces
Curly braces (also referred to as just “braces” or as “curly brackets”) are a major part of the C programming language. They are used in several different constructs, outlined below, and this can sometimes be confusing for beginners.
An opening curly brace “{“ must always be followed by a closing curly brace “}”. This is a condition that is often referred to as the braces being balanced. The Arduino IDE (integrated development environment) includes a convenient feature to check the balance of curly braces. Just select a brace, or even click the insertion point immediately following a brace, and its logical companion will be highlighted.
At present this feature is slightly buggy as the IDE will often find (incorrectly) a brace in text that has been “commented out.”
Beginning programmers, and programmers coming to C from the BASIC language often find using braces confusing or daunting. After all, the same curly braces replace the RETURN statement in a subroutine (function), the ENDIF statement in a conditional and the NEXT statement in a FOR loop.
Because the use of the curly brace is so varied, it is good programming practice to type the closing brace immediately after typing the opening brace when inserting a construct which requires curly braces. Then insert some carriage returns between your braces and begin inserting statements. Your braces, and your attitude, will never become unbalanced.
Unbalanced braces can often lead to cryptic, impenetrable compiler errors that can sometimes be hard to track down in a large program. Because of their varied usages, braces are also incredibly important to the syntax of a program and moving a brace one or two lines will often dramatically affect the meaning of a program.
The main uses of curly braces
Functions
void myfunction(datatype argument){ statements(s) }
Loops
while (boolean expression) { statement(s) } do { statement(s) } while (boolean expression); for (initialisation; termination condition; incrementing expr) { statement(s) }
Conditional statements
if (boolean expression) { statement(s) } else if (boolean expression) { statement(s) } else { statement(s) }
// (Single Line Comment)
Comments are lines in the program that are used to inform yourself or others about the way the program works. They are ignored by the compiler, and not exported to the processor, so they don’t take up any space on the Atmega chip.
Comments only purpose are to help you understand (or remember) how your program works or to inform others how your program works. There are two different ways of marking a line as a comment:
Example
x = 5; // This is a single line comment. Anything after the slashes is a comment // to the end of the line /\* this is multiline comment - use it to comment out whole blocks of code if (gwb == 0){ // single line comment is OK inside a multiline comment x = 3; /\* but not another multiline comment - this is invalid \*/ } // don't forget the "closing" comment - they have to be balanced! \*/
Tip
When experimenting with code, “commenting out” parts of your program is a convenient way to remove lines that may be buggy. This leaves the lines in the code, but turns them into comments, so the compiler just ignores them. This can be especially useful when trying to locate a problem, or when a program refuses to compile and the compiler error is cryptic or unhelpful.
/* */ (Multi Line Comment)
Comments are lines in the program that are used to inform yourself or others about the way the program works. They are ignored by the compiler, and not exported to the processor, so they don’t take up any space on the Atmega chip.
Comments only purpose are to help you understand (or remember) how your program works or to inform others how your program works. There are two different ways of marking a line as a comment:
Example
x = 5; // This is a single line comment. Anything after the slashes is a comment // to the end of the line /\* this is multiline comment - use it to comment out whole blocks of code if (gwb == 0){ // single line comment is OK inside a multiline comment x = 3; /\* but not another multiline comment - this is invalid \*/ } // don't forget the "closing" comment - they have to be balanced! \*/
Tip
When experimenting with code, “commenting out” parts of your program is a convenient way to remove lines that may be buggy. This leaves the lines in the code, but turns them into comments, so the compiler just ignores them. This can be especially useful when trying to locate a problem, or when a program refuses to compile and the compiler error is cryptic or unhelpful.
define
#define
is a useful C component that allows the programmer to give a name to a constant value before the program is compiled. Defined constants in arduino don’t take up any program memory space on the chip. The compiler will replace references to these constants with the defined value at compile time.
This can have some unwanted side effects though, if for example, a constant name that had been #defined is included in some other constant or variable name. In that case the text would be replaced by the #defined number (or text).
In general, the const keyword is preferred for defining constants and should be used instead of #define.
Arduino defines have the same syntax as C defines:
Syntax
#define constantName value
Note that the # is necessary.
Example
#define ledPin 3 // The compiler will replace any mention of ledPin with the value 3 at compile time.
Tip
There is no semicolon after the #define statement. If you include one, the compiler will throw cryptic errors further down the page.
#define ledPin 3; // this is an error
Similarly, including an equal sign after the #define statement will also generate a cryptic compiler error further down the page.
#define ledPin = 3 // this is also an error
See
include
include is used to include outside libraries in your sketch. This gives the programmer access to a large group of standard C libraries (groups of pre-made functions), and also libraries written especially for Arduino.
The main reference page for AVR C libraries (AVR is a reference to the Atmel chips on which the Arduino is based) is here.
Note that #include, similar to #define, has no semicolon terminator, and the compiler will yield cryptic error messages if you add one.
Example
This example includes a library that is used to put data into the program space flash instead of ram. This saves the ram space for dynamic memory needs and makes large lookup tables more practical.
#include <avr> prog_uint16_t myConstants[] PROGMEM = {0, 21140, 702 , 9128, 0, 25764, 8456, 0,0,0,0,0,0,0,0,29810,8968,29762,29762,4500};</avr>
= (Assignment Operator)
= assignment operator (single equal sign)
Stores the value to the right of the equal sign in the variable to the left of the equal sign.
The single equal sign in the C programming language is called the assignment operator. It has a different meaning than in algebra class where it indicated an equation or equality. The assignment operator tells the microcontroller to evaluate whatever value or expression is on the right side of the equal sign, and store it in the variable to the left of the equal sign.
Example
int sensVal; // declare an integer variable named sensVal sensVal = analogRead(0); // store the (digitized) input voltage at analog pin 0 in SensVal
Programming Tips
The variable on the left side of the assignment operator ( = sign ) needs to be able to hold the value stored in it. If it is not large enough to hold a value, the value stored in the variable will be incorrect.
Don’t confuse the assignment operator [=] (single equal sign) with the comparison operator [==] (double equal signs), which evaluates whether two expressions are equal.
See Also
+ - * /
Addition, Subtraction, Multiplication, & Division
Description
These operators return the sum, difference, product, or quotient (respectively) of the two operands. The operation is conducted using the data type of the operands, so, for example, 9 / 4
gives 2
since 9 and 4 are ints. This also means that the operation can overflow if the result is larger than that which can be stored in the data type (e.g. adding 1 to an int with the value 32,767 gives -32,768). If the operands are of different types, the “larger” type is used for the calculation.
If one of the numbers (operands) are of the type float or of type double, floating point math will be used for the calculation.
Examples
y = y + 3; x = x - 7; i = j \* 6; r = r / 5;
Syntax
result = value1 + value2; result = value1 - value2; result = value1 \* value2; result = value1 / value2;
Parameters:
value1: any variable or constant
value2: any variable or constant
Programming Tips:
- Know that integer constants default to int, so some constant calculations may overflow (e.g. 60 * 1000 will yield a negative result).
- Choose variable sizes that are large enough to hold the largest results from your calculations
- Know at what point your variable will “roll over” and also what happens in the other direction e.g. (0 - 1) OR (0 - - 32768)
- For math that requires fractions, use float variables, but be aware of their drawbacks: large size, slow computation speeds
- Use the cast operator e.g. (int)myFloat to convert one variable type to another on the fly.
% (Modulo)
% (modulo)
Description
Calculates the remainder when one integer is divided by another. It is useful for keeping a variable within a particular range (e.g. the size of an array).
Syntax
result = dividend % divisor
Parameters
dividend: the number to be divided
divisor: the number to divide by
Returns
the remainder
Examples
x = 7 % 5; // x now contains 2 x = 9 % 5; // x now contains 4 x = 5 % 5; // x now contains 0 x = 4 % 5; // x now contains 4
Example Code
/\* update one value in an array each time through a loop \*/ int values[10]; int i = 0; void setup() {} void loop() { values[i] = analogRead(0); i = (i + 1) % 10; // modulo operator rolls over variable }
==
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 greater than y)
<=
x <= y (x is less than or equal to y)
>=
x >= y (x is greater than or equal to y)
&&
&& (logical and)
True only if both operands are true, e.g.
if (digitalRead(2) == HIGH && digitalRead(3) == HIGH) { // read two switches // … }
is true only if both inputs are high.
||
|| (logical or)
True if either operand is true, e.g.
if (x > 0 || y > 0) { // … }
is true if either x or y is greater than 0.
!
! (not)
True if the operand is false, e.g.
if (!x) { // … }
is true if x is false (i.e. if x equals 0).
Bitwise AND (&)
Bitwise AND (&)
The bitwise operators perform their calculations at the bit level of variables. They help solve a wide range of common programming problems. Much of the material below is from an excellent tutorial on bitwise math wihch may be foundhere.
Description and Syntax
Below are descriptions and syntax for all of the operators. Further details may be found in the referenced tutorial.
Bitwise AND (&)
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. In a code fragment like:
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
Bitwise OR (|)
Bitwise OR (|)
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
Here is an example of the bitwise OR used in a snippet of C++ code:
int a = 92; // in binary: 0000000001011100 int b = 101; // in binary: 0000000001100101 int c = a | b; // result: 0000000001111101, or 125 in decimal.
Example Program for Arduino Uno
A common job for the bitwise AND and OR operators is what programmers call Read-Modify-Write on a port. On microcontrollers, a port is an 8 bit number that represents something about the condition of the pins. Writing to a port controls all of the pins at once.
PORTD is a built-in constant that refers to the output states of digital pins 0,1,2,3,4,5,6,7. If there is 1 in an bit position, then that pin is HIGH. (The pins already need to be set to outputs with the pinMode() command.) So if we writePORTD = B00110001;
we have made pins 0,4 & 5 HIGH. One slight hitch here is that we may also have changeed the state of Pins 0 & 1, which are used by the Arduino for serial communications so we may have interfered with serial communication.
Our algorithm for the program is:
- Get PORTD and clear out only the bits corresponding to the pins we wish to control (with bitwise AND).
- Combine the modified PORTD value with the new value for the pins under control (with biwise OR).
int i; // counter variable int j; void setup(){ DDRD = DDRD | B11111100; // set direction bits for pins 2 to 7, leave 0 and 1 untouched (xx | 00 == xx) // same as pinMode(pin, OUTPUT) for pins 2 to 7 Serial.begin(9600); } void loop(){ for (i=0; i\<64; i++){ PORTD = PORTD & B00000011; // clear out bits 2 - 7, leave pins 0 and 1 untouched (xx & 11 == xx) j = (i \<\< 2); // shift variable up to pins 2 - 7 - to avoid pins 0 and 1 PORTD = PORTD | j; // combine the port information with the new information for LED pins Serial.println(PORTD, BIN); // debug to show masking delay(100); } }
Bitwise XOR (^)
Bitwise XOR (^)
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 ^. This operator is very similar to the bitwise OR operator |, only it evaluates to 0 for a given bit position when both of the input bits for that position are 1:
0 0 1 1 operand1 0 1 0 1 operand2 ---------- 0 1 1 0 (operand1 ^ operand2) - returned result
Another way to look at bitwise XOR is that each bit in the result is a 1 if the input bits are different, or 0 if they are the same.
Here is a simple code example:
int x = 12; // binary: 1100 int y = 10; // binary: 1010 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 OR 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. Below is a program to blink digital pin 5.
// Blink\_Pin\_5 // demo for Exclusive OR void setup(){ DDRD = DDRD | B00100000; // set digital pin five as OUTPUT Serial.begin(9600); } void loop(){ PORTD = PORTD ^ B00100000; // invert bit 5 (digital pin 5), leave others untouched delay(100); }
Bitwise NOT (~)
Bitwise NOT (~)
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. For example:
0 1 operand1
---------- 1 0 ~ operand1
int a = 103; // binary: 0000000001100111 int b = ~a; // binary: 1111111110011000 = -104
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 ontwo’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.
Bitshift left (<<)
Bitshift right (>>)
bitshift left (<<), bitshift right (>>)
Description
From The Bitmath Tutorial in The Playground
There are two bit shift operators in C++: the left shift operator << and the right shift operator >>. These operators cause the bits in the left operand to be shifted left or right by the number of positions specified by the right operand.
More on bitwise math may be found here.
Syntax
variable << number_of_bits
variable >> number_of_bits
Parameters
variable - (byte, int, long) number_of_bits integer <= 32
Example:
int a = 5; // binary: 0000000000000101 int b = a \<\< 3; // binary: 0000000000101000, or 40 in decimal int c = b \>\> 3; // binary: 0000000000000101, or back to 5 like we started with
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 a = 5; // binary: 0000000000000101 int b = a \<\< 14; // 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:
1 \<\< 0 == 1 1 \<\< 1 == 2 1 \<\< 2 == 4 1 \<\< 3 == 8 ... 1 \<\< 8 == 256 1 \<\< 9 == 512 1 \<\< 10 == 1024 ...
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 = x \>\> 3; // 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 = (unsigned int)x \>\> 3; // 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.
++ –
++ (increment) / – (decrement)
Description
Increment or decrement a variable
Syntax
x++; // increment x by one and returns the old value of x ++x; // increment x by one and returns the new value of x x-- ; // decrement x by one and returns the old value of x --x ; // decrement x by one and returns the new value of x
Parameters
x: an integer or long (possibly unsigned)
Returns
The original or newly incremented / decremented value of the variable.
Examples
x = 2; y = ++x; // x now contains 3, y contains 3 y = x--; // x contains 2 again, y still contains 3
+=
x += y; // equivalent to the expression x = x + y;
-=
x -= y; // equivalent to the expression x = x - y;
*=
x *= y; // equivalent to the expression x = x * y;
/=
x /= y; // equivalent to the expression x = x / y;
%=
x %= y; // equivalent to the expression x = x % y;
Compound Bitwise AND (&=)
compound bitwise AND (&=)
Description
The compound bitwise AND operator (&=) is often used with a variable and a constant to force particular bits in a variable to the LOW state (to 0). This is often referred to in programming guides as “clearing” or “resetting” bits.
Syntax:
x &= y; // equivalent to x = x & y;
Parameters
x: a char, int or long variable
y: an integer constant or char, int, or long
Example:
First, a review of the Bitwise AND (&) operator
0 0 1 1 operand1 0 1 0 1 operand2 ---------- 0 0 0 1 (operand1 & operand2) - returned result
Bits that are “bitwise ANDed” with 0 are cleared to 0 so, if myByte is a byte variable,myByte & B00000000 = 0;
Bits that are “bitwise ANDed” with 1 are unchanged so, myByte & B11111111 = myByte;
Note: because we are dealing with bits in a bitwise operator - it is convenient to use the binary formatter withconstants. The numbers are still the same value in other representations, they are just not as easy to understand. Also, B00000000 is shown for clarity, but zero in any number format is zero (hmmm something philosophical there?)
Consequently - to clear (set to zero) bits 0 & 1 of a variable, while leaving the rest of the variable unchanged, use the compound bitwise AND operator (&=) with the constant B11111100
1 0 1 0 1 0 1 0 variable 1 1 1 1 1 1 0 0 mask ---------------------- 1 0 1 0 1 0 0 0 variable unchanged bits cleared
Here is the same representation with the variable’s bits replaced with the symbol x
x x x x x x x x variable 1 1 1 1 1 1 0 0 mask ---------------------- x x x x x x 0 0 variable unchanged bits cleared
So if:
myByte = B10101010; myByte &= B11111100 == B10101000;
Compound Bitwise OR (|=)
compound bitwise OR (|=)
Description
The compound bitwise OR operator (|=) is often used with a variable and a constant to “set” (set to 1) particular bits in a variable.
Syntax:
x |= y; // equivalent to x = x | y;
Parameters
x: a char, int or long variable
y: an integer constant or char, int, or long
Example:
First, a review of the Bitwise OR (|) operator
0 0 1 1 operand1 0 1 0 1 operand2 ---------- 0 1 1 1 (operand1 | operand2) - returned result
Bits that are “bitwise ORed” with 0 are unchanged, so if myByte is a byte variable,
myByte | B00000000 = myByte;
Bits that are “bitwise ORed” with 1 are set to 1 so:
myByte | B11111111 = B11111111;
Consequently - to set bits 0 & 1 of a variable, while leaving the rest of the variable unchanged, use the compound bitwise OR operator (|=) with the constant B00000011
1 0 1 0 1 0 1 0 variable 0 0 0 0 0 0 1 1 mask ---------------------- 1 0 1 0 1 0 1 1 variable unchanged bits set
Here is the same representation with the variables bits replaced with the symbol x
x x x x x x x x variable 0 0 0 0 0 0 1 1 mask ---------------------- x x x x x x 1 1 variable unchanged bits set
So if:
myByte = B10101010; myByte |= B00000011 == B10101011;
true and false
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.
HIGH and LOW
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
The meaning of HIGH
(in reference to a pin) is somewhat different depending on whether a pin is set to an INPUT
orOUTPUT
. 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 volts is present at the pin (5V boards);
- a voltage greater than 2 volts 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 pulledLOW
by external circuitry. This is how INPUT_PULLUP
works and is described below in more detail.
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 reportLOW
if:
- a voltage less than 3 volts is present at the pin (5V boards);
- a voltage less than 2 volts 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).
INPUT
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.
If you have your pin configured as an INPUT
, and are reading a switch, when the switch is in the open state the input pin will be “floating”, resulting in unpredictable results. In order to assure a proper reading when the switch is open, a pull-up or pull-down resistor must be used. The purpose of this resistor is to pull the pin to a known state when the switch is open. A 10 K ohm resistor is usually chosen, as it is a low enough value to reliably prevent a floating input, and at the same time a high enough value to not not draw too much current when the switch is closed. See the Digital Read Serial tutorial for more information.
If a pull-down resistor is used, the input pin will be LOW
when the switch is open and HIGH
when the switch is closed.
If a pull-up resistor is used, the input pin will be HIGH
when the switch is open and LOW
when the switch is closed.
INPUT_PULLUP
Pins Configured as INPUT_PULLUP
The Atmega microcontroller on the Arduino has internal pull-up resistors (resistors that connect to power internally) that you can access. If you prefer to use these instead of external pull-up resistors, you can use the INPUT_PULLUPargument in pinMode()
.
See the Input Pullup Serial tutorial for an example of this in use.
Pins configured as inputs with either INPUT
or INPUT_PULLUP
can be damaged or destroyed if they are connected to voltages below ground (negative voltages) or above the positive power rail (5V or 3V).
OUTPUT
Pins Configured as Outputs
Pins configured as OUTPUT with pinMode()
are said to be in a low-impedance state. This means that they can provide a substantial amount of current to other circuits. Atmega pins can source (provide current) or sink (absorb current) up to 40 mA (milliamps) of current to other devices/circuits. This makes them useful for powering LEDsbecause LEDs typically use less than 40 mA. Loads greater than 40 mA (e.g. motors) will require a transistor or other interface circuitry.
Pins configured as outputs can be damaged or destroyed if they are connected to either the ground or positive power rails.
LED_BUILTIN
Defining built-ins: LED_BUILTIN
Most Arduino boards have a pin connected to an on-board LED in series with a resistor. The constant LED_BUILTIN
is the number of the pin to which the on-board LED is connected. Most boards have this LED connected to digital pin 13.
Integer Constants
Integer Constants
Integer constants are numbers used directly in a sketch, like 123
. By default, these numbers are treated as int’s 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) B1111011 leading 'B' only works with 8 bit values (0 to 255) 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 is 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:
101 // same as 101 decimal ((1 \* 10^2) + (0 \* 10^1) + 1)
Binary is base two. Only characters 0 and 1 are valid.
Example:
B101 // same as 5 decimal ((1 \* 2^2) + (0 \* 2^1) + 1)
The binary formatter only works on bytes (8 bits) between 0 (B0) and 255 (B11111111). If it is convenient to input an int (16 bits) in binary form you can do it a two-step procedure such as:
myInt = (B11001100 \* 256) + B10101010; // B11001100 is the high byte
Octal is base eight. Only characters 0 through 7 are valid. Octal values are indicated by the prefix “0”
Example:
0101 // same as 65 decimal ((1 \* 8^2) + (0 \* 8^1) + 1)
Warning
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 (or hex) is base sixteen. 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 syted in upper or lower case (a-f).
Example:
0x101 // same as 257 decimal ((1 \* 16^2) + (0 \* 16^1) + 1)
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
floating point constants
floating point constants
Similar to integer constants, floating point constants are used to make code more readable. Floating point constants are swapped at compile time for the value to which the expression evaluates.
Examples:
n = .005;
Floating point constants can also be expressed in a variety of scientific notation. ‘E’ and ‘e’ are both accepted as valid exponent indicators.
floating-point evaluates to: also evaluates to: constant 10.0 10 2.34E5 2.34 \* 10^5 234000 67e-12 67.0 \* 10^-12 .000000000067
void
void
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:
// actions are performed in the functions "setup" and "loop" // but no information is reported to the larger program void setup() { // ... } void loop() { // ... }
boolean
boolean
A boolean holds one of two values, true or false. (Each boolean variable occupies one byte of memory.)
Example
int LEDpin = 5; // LED on pin 5 int switchPin = 13; // momentary switch on 13, other side connected to ground boolean 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 } }