Arduino C Language Reference - Eidan Yoson
Arduino C Language Reference - Eidan Yoson
Digital I/O
digitalRead()
digitalWrite()
pinMode()
Analog I/O
analogRead()
analogReference()
analogWrite()
Zero, Due & MKR Family
analogReadResolution()
analogWriteResolution()
Advanced I/O
noTone()
pulseIn()
pulseInLong()
shiftIn()
shiftOut()
tone()
Time
delay()
delayMicroseconds()
micros()
millis()
Math
abs()
constrain()
map()
max()
min()
pow()
sq()
sqrt()
Trigonometry
cos()
sin()
tan()
Characters
isAlpha()
isAlphaNumeric()
isAscii()
isControl()
isDigit()
isGraph()
isHexadecimalDigit()
isLowerCase()
isPrintable()
isPunct()
isSpace()
isUpperCase()
isWhitespace()
Random Numbers
random()
randomSeed()
Bits and Bytes
bit()
bitClear()
bitRead()
bitSet()
bitWrite()
highByte()
lowByte()
External Interrupts
attachInterrupt()
detachInterrupt()
Interrupts
interrupts()
noInterrupts()
Communication
Print
Serial
SPI
Stream
Wire
USB
Keyboard
Mouse
Variables
Arduino data types and constants.
Constants
HIGH | LOW
INPUT | OUTPUT | INPUT_PULLUP
LED_BUILTIN
true | false
Floating Point Constants
Integer Constants
Conversion
(unsigned int)
(unsigned long)
byte()
char()
float()
int()
long()
word()
Data Types
array
bool
boolean
byte
char
double
float
int
long
short
size_t
string
String()
unsigned char
unsigned int
unsigned long
void
word
Variable Scope & Qualifiers
const
scope
static
volatile
Utilities
PROGMEM
sizeof()
Structure
The elements of Arduino (C++) code.
Sketch
loop()
setup()
Control Structure
break
continue
do...while
else
for
goto
if
return
switch...case
while
Further Syntax
#define (define)
#include (include)
/* */ (block comment)
// (single line comment)
; (semicolon)
{} (curly braces)
Arithmetic Operators
% (remainder)
* (multiplication)
+ (addition)
- (subtraction)
/ (division)
= (assignment operator)
Comparison Operators
!= (not equal to)
< (less than)
<= (less than or equal to)
== (equal to)
> (greater than)
>= (greater than or equal to)
Boolean Operators
! (logical not)
&& (logical and)
|| (logical or)
Pointer Access Operators
& (reference operator)
* (dereference operator)
Bitwise Operators
& (bitwise and)
<< (bitshift left)
>> (bitshift right)
^ (bitwise xor)
| (bitwise or)
~ (bitwise not)
Compound Operators
%= (compound remainder)
&= (compound bitwise and)
*= (compound multiplication)
++ (increment)
+= (compound addition)
-- (decrement)
-= (compound subtraction)
/= (compound division)
^= (compound bitwise xor)
|= (compound bitwise or)
Part 1: Functions
digitalRead()
[Digital I/O]
Description
Reads the value from a specified digital pin, either HIGH or LOW.
Syntax
digitalRead(pin)
Parameters
Returns
HIGH or LOW
Example Code
void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin 13 as output
pinMode(inPin, INPUT); // sets the digital pin 7 as input
}
void loop() {
val = digitalRead(inPin); // read the input pin
digitalWrite(ledPin, val); // sets the LED to the button's value
}
Notes and Warnings
The analog input pins can be used as digital pins, referred to as A0,
A1, etc. The exception is the Arduino Nano, Pro Mini, and Mini’s A6
and A7 pins, which can only be used as analog inputs.
See also
digitalWrite()
[Digital I/O]
Description
digitalWrite(pin, value)
Parameters
Returns
Nothing
Example Code
void setup() {
pinMode(13, OUTPUT); // sets the digital pin 13 as output
}
void loop() {
digitalWrite(13, HIGH); // sets the digital pin 13 on
delay(1000); // waits for a second
digitalWrite(13, LOW); // sets the digital pin 13 off
delay(1000); // waits for a second
}
The analog input pins can be used as digital pins, referred to as A0,
A1, etc. The exception is the Arduino Nano, Pro Mini, and Mini’s A6
and A7 pins, which can only be used as analog inputs.
See also
Description
Syntax
pinMode(pin, mode)
Parameters
Returns
Nothing
Example Code
The code makes the digital pin 13 OUTPUT and Toggles it HIGH and LOW
void setup() {
pinMode(13, OUTPUT); // sets the digital pin 13 as output
}
void loop() {
digitalWrite(13, HIGH); // sets the digital pin 13 on
delay(1000); // waits for a second
digitalWrite(13, LOW); // sets the digital pin 13 off
delay(1000); // waits for a second
}
The analog input pins can be used as digital pins, referred to as A0,
A1, etc.
See also
analogRead()
[Analog I/O]
Description
Reads the value from the specified analog pin. Arduino boards
contain a multichannel, 10-bit analog to digital converter. This
means that it will map input voltages between 0 and the operating
voltage(5V or 3.3V) into integer values between 0 and 1023. On an
Arduino UNO, for example, this yields a resolution between readings
of: 5 volts / 1024 units or, 0.0049 volts (4.9 mV) per unit. See the
table below for the usable pins, operating voltage and maximum
resolution for some Arduino boards.
Syntax
analogRead(pin)
Parameters
pin: the name of the analog input pin to read from (A0 to A5 on
most boards, A0 to A6 on MKR boards, A0 to A7 on the Mini and
Nano, A0 to A15 on the Mega).
Returns
Example Code
void setup() {
Serial.begin(9600); // setup serial
}
void loop() {
val = analogRead(analogPin); // read the input pin
Serial.println(val); // debug value
}
See also
LANGUAGE analogReadResolution()
analogReference()
[Analog I/O]
Description
Configures the reference voltage used for analog input (i.e. the
value used as the top of the input range). The options are:
Syntax
analogReference(type)
Parameters
Returns
Nothing
Notes and Warnings
See also
analogWrite()
[Analog I/O]
Description
You do not need to call pinMode() to set the pin as an output before
calling analogWrite().
The analogWrite function has nothing to do with the analog pins or
the analogRead function.
Syntax
analogWrite(pin, value)
Parameters
pin: the Arduino pin to write to. Allowed data types: int.
value: the duty cycle: between 0 (always off) and 255 (always on).
Allowed data types: int.
Returns
Nothing
Example Code
Sets the output to the LED proportional to the value read from the
potentiometer.
void setup() {
pinMode(ledPin, OUTPUT); // sets the pin as output
}
void loop() {
val = analogRead(analogPin); // read the input pin
analogWrite(ledPin, val / 4); // analogRead values go from 0 to
1023, analogWrite values from 0 to 255
}
See also
LANGUAGE analogWriteResolution()
DEFINITION PWM
EXAMPLE Blink
analogReadResolution()
[Zero, Due & MKR Family]
Description
The Zero, Due, MKR family and Nano 33 (BLE and IoT) boards
have 12-bit ADC capabilities that can be accessed by changing the
resolution to 12. This will return values from analogRead() between 0
and 4095.
The Portenta H7 has a 16 bit ADC, which will allow values between
0 and 65535.
Syntax
analogReadResolution(bits)
Parameters
Returns
Nothing
Example Code
void setup() {
// open a serial connection
Serial.begin(9600);
}
void loop() {
// read the input on A0 at default resolution (10 bits)
// and send it out the serial connection
analogReadResolution(10);
Serial.print("ADC 10-bit (default) : ");
Serial.print(analogRead(A0));
See also
LANGUAGE analogRead()
analogWriteResolution()
[Zero, Due & MKR Family]
Description
By setting the write resolution to 12, you can use analogWrite() with
values between 0 and 4095 to exploit the full DAC resolution or to
set the PWM signal without rolling over.
By setting the write resolution to 10, you can use analogWrite() with
values between 0 and 1023 to exploit the full DAC resolution
4 pins which default to 8-bit PWM, like the AVR-based boards. These
can be changed from 8 (default) to 12-bit resolution.
analogWriteResolution(bits)
Parameters
Returns
Nothing
Example Code
Explain Code
void setup() {
// open a serial connection
Serial.begin(9600);
// make our digital pin an output
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
}
void loop() {
// read the input on A0 and map it to a PWM pin
// with an attached LED
int sensorVal = analogRead(A0);
Serial.print("Analog Read) : ");
Serial.print(sensorVal);
delay(5);
}
See also
LANGUAGE analogWrite()
LANGUAGE analogRead()
LANGUAGE map()
Description
Syntax
noTone(pin)
Parameters
Returns
Nothing
See also
pulseIn()
[Advanced I/O]
Description
The timing of this function has been determined empirically and will
probably show errors in longer pulses. Works on pulses from 10
microseconds to 3 minutes in length.
Syntax
pulseIn(pin, value)
pulseIn(pin, value, timeout)
Parameters
pin: the number of the Arduino pin on which you want to read the
pulse. Allowed data types: int.
value: type of pulse to read: either HIGH or LOW. Allowed data
types: int.
timeout (optional): the number of microseconds to wait for the pulse
to start; default is one second. Allowed data types: unsigned long.
Returns
The length of the pulse (in microseconds) or 0 if no pulse started
before the timeout. Data type: unsigned long.
Example Code
int pin = 7;
unsigned long duration;
void setup() {
Serial.begin(9600);
pinMode(pin, INPUT);
}
void loop() {
duration = pulseIn(pin, HIGH);
Serial.println(duration);
}
See also
pulseInLong()
[Advanced I/O]
Description
Syntax
pulseInLong(pin, value)
pulseInLong(pin, value, timeout)
Parameters
pin: the number of the Arduino pin on which you want to read the
pulse. Allowed data types: int.
value: type of pulse to read: either HIGH or LOW. Allowed data
types: int.
timeout (optional): the number of microseconds to wait for the pulse
to start; default is one second. Allowed data types: unsigned long.
Returns
Example Code
int pin = 7;
unsigned long duration;
void setup() {
Serial.begin(9600);
pinMode(pin, INPUT);
}
void loop() {
duration = pulseInLong(pin, HIGH);
Serial.println(duration);
}
shiftIn()
[Advanced I/O]
Description
Shifts in a byte of data one bit at a time. Starts from either the most
(i.e. the leftmost) or least (rightmost) significant bit. For each bit,
the clock pin is pulled high, the next bit is read from the data line,
and then the clock pin is taken low.
Syntax
Parameters
dataPin: the pin on which to input each bit. Allowed data types: int.
clockPin: the pin to toggle to signal a read from dataPin.
bitOrder: which order to shift in the bits;
either MSBFIRST or LSBFIRST. (Most Significant Bit First, or, Least
Significant Bit First).
Returns
shiftOut()
[Advanced I/O]
Description
Shifts out a byte of data one bit at a time. Starts from either the
most (i.e. the leftmost) or least (rightmost) significant bit. Each bit
is written in turn to a data pin, after which a clock pin is pulsed
(taken high, then low) to indicate that the bit is available.
Syntax
Parameters
Returns
Nothing
Example Code
//**************************************************************//
// Name : shiftOutCode, Hello World //
// Author : Carlyn Maw,Tom Igoe //
// Date : 25 Oct, 2006 //
// Version : 1.0 //
// Notes : Code for using a 74HC595 Shift Register //
// : to count from 0 to 255 //
//****************************************************************
void setup() {
//set pins to output because they are addressed in the main loop
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT);
pinMode(dataPin, OUTPUT);
}
void loop() {
//count up routine
for (int j = 0; j < 256; j++) {
//ground latchPin and hold low for as long as you are
transmitting
digitalWrite(latchPin, LOW);
shiftOut(dataPin, clockPin, LSBFIRST, j);
//return the latch pin high to signal chip that it
//no longer needs to listen for information
digitalWrite(latchPin, HIGH);
delay(1000);
}
}
Notes and Warnings
tone()
[Advanced I/O]
Description
Use of the tone() function will interfere with PWM output on pins 3
and 11 (on boards other than the Mega).
It is not possible to generate tones lower than 31Hz. For technical
details, see Brett Hagman’s notes.
Syntax
tone(pin, frequency)
tone(pin, frequency, duration)
Parameters
Returns
Nothing
See also
LANGUAGE analogWrite() - Tone Melody - Pitch Follower
Description
Syntax
delay(ms)
Parameters
Returns
Nothing
Example Code
The code pauses the program for one second before toggling the
output pin.
void setup() {
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop() {
digitalWrite(ledPin, HIGH); // sets the LED on
delay(1000); // waits for a second
digitalWrite(ledPin, LOW); // sets the LED off
delay(1000); // waits for a second
}
Notes and Warnings
See also
delayMicroseconds()
[Time]
Description
Syntax
delayMicroseconds(us)
Parameters
Returns
Nothing
Example Code
void setup() {
pinMode(outPin, OUTPUT); // sets the digital pin as output
}
void loop() {
digitalWrite(outPin, HIGH); // sets the pin on
delayMicroseconds(50); // pauses for 50 microseconds
digitalWrite(outPin, LOW); // sets the pin off
delayMicroseconds(50); // pauses for 50 microseconds
}
micros()
[Time]
Description
Syntax
time = micros()
Parameters
None
Returns
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Time: ");
time = micros();
millis()
[Time]
Description
Syntax
time = millis()
Parameters
None
Returns
Example Code
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Time: ");
myTime = millis();
The return value for millis() is of type unsigned long, logic errors
may occur if a programmer tries to do arithmetic with smaller data
types such as int. Even signed long may encounter errors as its
maximum value is half that of its unsigned counterpart.
See also
abs()
[Math]
Description
Syntax
abs(x)
Parameters
x: the number
Returns
Example Code
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB
port only
}
int x = 42;
Serial.print("The absolute value of ");
Serial.print(x);
Serial.print(" is ");
Serial.println(abs(x));
x = -42;
Serial.print("The absolute value of ");
Serial.print(x);
Serial.print(" is ");
Serial.println(abs(x));
}
void loop() {
}
constrain()
[Math]
Description
Syntax
constrain(x, a, b)
Parameters
Returns
x: if x is between a and b.
a: if x is less than a.
b: if x is greater than b.
Example Code
map()
[Math]
Description
The map() function uses integer math so will not generate fractions,
when the math might indicate that it should do so. Fractional
remainders are truncated, and are not rounded or averaged.
Syntax
Parameters
Returns
Example Code
/* Map an analog value to 8 bits (0 to 255) */
void setup() {}
void loop() {
int val = analogRead(0);
val = map(val, 0, 1023, 0, 255);
analogWrite(9, val);
}
Appendix
Description
Syntax
max(x, y)
Parameters
Returns
Example Code
min()
[Math]
Description
Syntax
min(x, y)
Parameters
Returns
Example Code
min(a, 100);
a++; // use this instead - keep other math outside the function
pow()
[Math]
Description
Syntax
pow(base, exponent)
Parameters
Returns
z = pow(x, y);
See the (fscale) sketch for a more complex example of the use
of pow().
sq()
[Math]
Description
Syntax
sq(x)
Parameters
Returns
sqrt()
[Math]
Description
Syntax
sqrt(x)
Parameters
Returns
Description
Syntax
cos(rad)
Parameters
Returns
sin()
[Trigonometry]
Description
Syntax
sin(rad)
Parameters
Returns
tan()
[Trigonometry]
Description
Syntax
tan(rad)
Parameters
Returns
Description
Syntax
isAlpha(thisChar)
Parameters
Returns
Example Code
if (isAlpha(myChar)) { // tests if myChar is a letter
Serial.println("The character is a letter");
}
else {
Serial.println("The character is not a letter");
}
isAlphaNumeric()
[Characters]
Description
isAlphaNumeric(thisChar)
Parameters
Returns
Example Code
if (isAlphaNumeric(myChar)) { // tests if myChar isa letter or a
number
Serial.println("The character is alphanumeric");
}
else {
Serial.println("The character is not alphanumeric");
}
isAscii()
[Characters]
Description
Syntax
isAscii(thisChar)
Parameters
Example Code
if (isAscii(myChar)) { // tests if myChar is an Ascii character
Serial.println("The character is Ascii");
}
else {
Serial.println("The character is not Ascii");
}
isControl()
[Characters]
Description
Syntax
isControl(thisChar)
Parameters
Returns
Example Code
if (isControl(myChar)) { // tests if myChar is a control character
Serial.println("The character is a control character");
}
else {
Serial.println("The character is not a control character");
}
isDigit()
[Characters]
Description
Syntax
isDigit(thisChar)
Parameters
Returns
Example Code
if (isDigit(myChar)) { // tests if myChar is a digit
Serial.println("The character is a number");
}
else {
Serial.println("The character is not a number");
}
isGraph()
[Characters]
Description
isGraph(thisChar)
Parameters
Returns
Example Code
if (isGraph(myChar)) { // tests if myChar is a printable character
but not a blank space.
Serial.println("The character is printable");
}
else {
Serial.println("The character is not printable");
}
isHexadecimalDigit()
[Characters]
Description
Syntax
isHexadecimalDigit(thisChar)
Parameters
Example Code
if (isHexadecimalDigit(myChar)) { // tests if myChar is an
hexadecimal digit
Serial.println("The character is an hexadecimal digit");
}
else {
Serial.println("The character is not an hexadecimal digit");
}
isLowerCase()
[Characters]
Syntax
isLowerCase(thisChar)
Parameters
Returns
Example Code
if (isLowerCase(myChar)) { // tests if myChar is a lower case
letter
Serial.println("The character is lower case");
}
else {
Serial.println("The character is not lower case");
}
isPrintable()
[Characters]
Description
Syntax
isPrintable(thisChar)
Parameters
Returns
Example Code
if (isPrintable(myChar)) { // tests if myChar is printable char
Serial.println("The character is printable");
}
else {
Serial.println("The character is not printable");
}
isPunct()
[Characters]
Description
isPunct(thisChar)
Parameters
Returns
Example Code
if (isPunct(myChar)) { // tests if myChar is a punctuation
character
Serial.println("The character is a punctuation");
}
else {
Serial.println("The character is not a punctuation");
}
isSpace()
[Characters]
Description
Syntax
isSpace(thisChar)
Parameters
Example Code
if (isSpace(myChar)) { // tests if myChar is a white-space
character
Serial.println("The character is white-space");
}
else {
Serial.println("The character is not white-space");
}
isUpperCase()
[Characters]
Syntax
isUpperCase(thisChar)
Parameters
Returns
Example Code
if (isUpperCase(myChar)) { // tests if myChar is an upper case
letter
Serial.println("The character is upper case");
}
else {
Serial.println("The character is not upper case");
}
isWhitespace()
[Characters]
Description
Syntax
isWhitespace(thisChar)
Parameters
Returns
Example Code
if (isWhitespace(myChar)) { // tests if myChar is a space character
Serial.println("The character is a space or tab");
}
else {
Serial.println("The character is not a space or tab");
}
random()
[Random Numbers]
Syntax
random(max)
random(min, max)
Parameters
Returns
Example Code
long randNumber;
void setup() {
Serial.begin(9600);
void loop() {
// print a random number from 0 to 299
randNumber = random(300);
Serial.println(randNumber);
randomSeed()
[Random Numbers]
Syntax
randomSeed(seed)
Parameters
Returns
Nothing
Example Code
long randNumber;
void setup() {
Serial.begin(9600);
randomSeed(analogRead(0));
}
void loop() {
randNumber = random(300);
Serial.println(randNumber);
delay(50);
}
Description
Syntax
bit(n)
Parameters
Returns
bitClear()
[Bits and Bytes]
Description
Syntax
bitClear(x, n)
Parameters
Returns
Example Code
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB
port only
}
int x = 6;
int n = 1;
Serial.print(bitClear(x, n)); // print the output of
bitClear(x,n)
}
void loop() {
}
bitRead()
[Bits and Bytes]
Description
bitRead(x, n)
Parameters
Returns
bitSet()
[Bits and Bytes]
Syntax
bitSet(x, n)
Parameters
Returns
Nothing
bitWrite()
[Bits and Bytes]
Description
Syntax
bitWrite(x, n, b)
Parameters
Returns
Nothing
Example Code
void setup() {
Serial.begin(9600);
while (!Serial) {} // wait for serial port to connect. Needed
for native USB port only
byte x = 0b10000000; // the 0b prefix indicates a binary
constant
Serial.println(x, BIN); // 10000000
bitWrite(x, 0, 1); // write 1 to the least significant bit of x
Serial.println(x, BIN); // 10000001
}
void loop() {}
highByte()
[Bits and Bytes]
Description
Syntax
highByte(x)
Parameters
Returns
See also
LANGUAGE word()
lowByte()
[Bits and Bytes]
Description
Syntax
lowByte(x)
Parameters
Returns
See also
LANGUAGE word()
attachInterrupt()
[External Interrupts]
Mega, Mega2560, MegaADK 2, 3, 18, 19, 20, 21 (pins 20 & 21 are not
Note
Inside the attached function, delay() won’t work and the value
returned by millis() will not increment. Serial data received while in
the function may be lost. You should declare as volatile any
variables that you modify within the attached function. See the
section on ISRs below for more information.
Using Interrupts
Interrupts are useful for making things happen automatically in
microcontroller programs and can help solve timing problems. Good
tasks for using an interrupt may include reading a rotary encoder, or
monitoring user input.
Typically global variables are used to pass data between an ISR and
the main program. To make sure variables shared between an ISR
and the main program are updated correctly, declare them
as volatile.
Syntax
attachInterrupt(digitalPinToInterrupt(pin), ISR,
mode) (recommended)
attachInterrupt(interrupt, ISR, mode) (not recommended)
attachInterrupt(pin, ISR, mode) (Not recommended. Additionally,
this syntax only works on Arduino SAMD Boards, Uno WiFi Rev2,
Due, and 101.)
Parameters
Returns
Nothing
Example Code
const byte ledPin = 13;
const byte interruptPin = 2;
volatile byte state = LOW;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), blink,
CHANGE);
}
void loop() {
digitalWrite(ledPin, state);
}
void blink() {
state = !state;
}
Interrupt Numbers
Note that in the table below, the interrupt numbers refer to the
number to be passed to attachInterrupt(). For historical reasons,
this numbering does not always correspond directly to the interrupt
numbering on the ATmega chip (e.g. int.0 corresponds to INT4 on
the ATmega2560 chip).
Uno, Ethernet 2 3
Mega2560 2 3 21 20 19 18
detachInterrupt()
[External Interrupts]
Description
Syntax
detachInterrupt(digitalPinToInterrupt(pin)) (recommended)
detachInterrupt(interrupt) (not recommended)
detachInterrupt(pin) (Not recommended. Additionally, this syntax
only works on Arduino SAMD Boards, Uno WiFi Rev2, Due, and 101.)
Parameters
Returns
Nothing
interrupts()
[Interrupts]
Description
Syntax
interrupts()
Parameters
None
Returns
Nothing
Example Code
void setup() {}
void loop() {
noInterrupts();
// critical, time-sensitive code here
interrupts();
// other code here
}
noInterrupts()
[Interrupts]
Description
Syntax
noInterrupts()
Parameters
None
Returns
Nothing
Print
[Communication]
Description
Serial
LiquidCrystal
Ethernet
Wifi
Functions
write()
print()
println()
write()
Description
Syntax
Parameters
Returns
Example
#include <Wire.h>
byte val = 0;
void setup() {
Wire.begin(); // Join I2C bus
}
void loop() {
Wire.beginTransmission(44); // Transmit to device number 44
(0x2C)
delay(500);
}
Serial.print()
Description
Serial.print(F("Hello World"))
Syntax
Serial.print(val)
Serial.print(val, format)
Parameters
Serial: serial port object. See the list of available serial ports for
each board on the Serial main page.
val: the value to print. Allowed data types: any data type.
Returns
Example Code
/*
Uses a for loop to print numbers in various formats.
*/
void setup() {
Serial.begin(9600); // open the serial port at 9600 bps:
}
void loop() {
// print labels
Serial.print("NO FORMAT"); // prints a label
Serial.print("\t"); // prints a tab
Serial.print("DEC");
Serial.print("\t");
Serial.print("HEX");
Serial.print("\t");
Serial.print("OCT");
Serial.print("\t");
Serial.print("BIN");
Serial.println(); // carriage return after the last label
for (int x = 0; x < 64; x++) { // only part of the ASCII chart,
change to suit
// print it out in many formats:
Serial.print(x); // print as an ASCII-encoded decimal -
same as "DEC"
Serial.print("\t\t"); // prints two tabs to accomodate the
label lenght
See also
Description
Syntax
Serial.println(val)
Serial.println(val, format)
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
val: the value to print. Allowed data types: any data type.
format: specifies the number base (for integral data types) or
number of decimal places (for floating point types).
Returns
Example Code
/*
Analog input reads an analog input on analog in 0, prints the
value out.
created 24 March 2006
by Tom Igoe
*/
void setup() {
// open the serial port at 9600 bps:
Serial.begin(9600);
}
void loop() {
// read the analog input on pin 0:
analogValue = analogRead(0);
BOARD USB CDC SERIAL PINS SERIAL1 PINS SERIAL2 PINS SERIAL3 PINS
NAME
Uno, 0(RX), 1(TX)
Nano, Mini
Mega 0(RX), 1(TX) 19(RX), 17(RX), 15(RX),
18(TX) 16(TX) 14(TX)
Leonardo, Serial 0(RX), 1(TX)
Micro, Yún
Uno WiFi Connected to 0(RX), 1(TX) Connected to
Rev.2 USB NINA
MKR Serial 13(RX),
boards 14(TX)
Zero SerialUSB Connected to 0(RX), 1(TX)
(Native USB Programming
Port only) Port
Due SerialUSB 0(RX), 1(TX) 19(RX), 17(RX), 15(RX),
(Native USB 18(TX) 16(TX) 14(TX)
Port only)
101 Serial 0(RX), 1(TX)
On Uno, Nano, Mini, and Mega, pins 0 and 1 are used for
communication with the computer. Connecting anything to these
pins can interfere with that communication, including causing failed
uploads to the board.
Functions
if(Serial)
available()
availableForWrite()
begin()
end()
find()
findUntil()
flush()
parseFloat()
parseInt()
peek()
print()
println()
read()
readBytes()
readBytesUntil()
readString()
readStringUntil()
setTimeout()
write()
serialEvent()
See also
Description
Syntax
if (Serial)
Parameters
None
Returns
Returns true if the specified serial port is available. This will only
return false if querying the Leonardo’s USB CDC serial connection
before it is ready. Data type: bool.
Example Code
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB
}
}
void loop() {
//proceed normally
}
Serial.available()
Get the number of bytes (characters) available for reading from the
serial port. This is data that’s already arrived and stored in the serial
receive buffer (which holds 64 bytes).
Syntax
Serial.available()
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
Returns
Example Code
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600
bps
}
void loop() {
// reply only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
void setup() {
Serial.begin(9600);
Serial1.begin(9600);
}
void loop() {
// read from port 0, send to port 1:
if (Serial.available()) {
int inByte = Serial.read();
Serial1.print(inByte, DEC);
}
// read from port 1, send to port 0:
if (Serial1.available()) {
int inByte = Serial1.read();
Serial.print(inByte, DEC);
}
}
Serial.availableForWrite()
Syntax
Serial.availableForWrite()
Parameters
Serial: serial port object. See the list of available serial ports for
each board on the Serial main page.
Returns
Description
Sets the data rate in bits per second (baud) for serial data
transmission. For communicating with Serial Monitor, make sure to
use one of the baud rates listed in the menu at the bottom right
corner of its screen. You can, however, specify other rates - for
example, to communicate over pins 0 and 1 with a component that
requires a particular baud rate.
Syntax
Serial.begin(speed)
Serial.begin(speed, config)
Parameters
Serial: serial port object. See the list of available serial ports for
each board on the Serial main page.
speed: in bits per second (baud). Allowed data types: long.
config: sets data, parity, and stop bits. Valid values are:
SERIAL_5N1
SERIAL_6N1
SERIAL_7N1
SERIAL_8N1 (the default)
SERIAL_5N2
SERIAL_6N2
SERIAL_7N2
SERIAL_8N2
SERIAL_5E1: even parity
SERIAL_6E1
SERIAL_7E1
SERIAL_8E1
SERIAL_5E2
SERIAL_6E2
SERIAL_7E2
SERIAL_8E2
SERIAL_5O1: odd parity
SERIAL_6O1
SERIAL_7O1
SERIAL_8O1
SERIAL_5O2
SERIAL_6O2
SERIAL_7O2
SERIAL_8O2
Returns
Nothing
Example Code
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to
9600 bps
}
void loop() {}
void setup() {
Serial.begin(9600);
Serial1.begin(38400);
Serial2.begin(19200);
Serial3.begin(4800);
Serial.println("Hello Computer");
Serial1.println("Hello Serial 1");
Serial2.println("Hello Serial 2");
Serial3.println("Hello Serial 3");
}
void loop() {}
The only config value supported for Serial1 on the Arduino Nano 33
BLE and Nano 33 BLE Sense boards is SERIAL_8N1.
Serial.end()
Description
Syntax
Serial.end()
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
Returns
Nothing
Serial.find()
Description
Serial.find() reads data from the serial buffer until the target is
found. The function returns true if target is found, false if it times
out.
Syntax
Serial.find(target)
Serial.find(target, length)
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
target: the string to search for. Allowed data types: char.
length: length of the target. Allowed data types: size_t.
Returns
Serial.findUntil()
Description
Syntax
Serial.findUntil(target, terminal)
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
target: the string to search for. Allowed data types: char.
terminal: the terminal string in the search. Allowed data types: char.
Returns
Serial.parseFloat()
Description
Serial.parseFloat()
Serial.parseFloat(lookahead)
Serial.parseFloat(lookahead, ignore)
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
lookahead: the mode used to look ahead in the stream for a floating
point number. Allowed data types: LookaheadMode.
Allowed lookahead values:
ignore: used to skip the indicated char in the search. Used for
example to skip thousands divider. Allowed data types: char
Returns
Description
Looks for the next valid integer in the incoming serial. The function
terminates if it times out (see Serial.setTimeout()).
In particular:
Syntax
Serial.parseInt()
Serial.parseInt(lookahead)
Serial.parseInt(lookahead, ignore)
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
lookahead: the mode used to look ahead in the stream for an
integer. Allowed data types: LookaheadMode.
Allowed lookahead values:
SKIP_ALL: all characters other than digits or a minus sign are ignored
when scanning the stream for an integer. This is the default mode.
ignore: used to skip the indicated char in the search. Used for
example to skip thousands divider. Allowed data types: char
Returns
Serial.peek()
Description
Syntax
Serial.peek()
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
Returns
Serial.print(F("Hello World"))
To send data without conversion to its representation as characters,
use Serial.write().
Syntax
Serial.print(val)
Serial.print(val, format)
Parameters
Serial: serial port object. See the list of available serial ports for
each board on the Serial main page.
val: the value to print. Allowed data types: any data type.
Returns
Example Code
/*
Uses a for loop to print numbers in various formats.
*/
void setup() {
Serial.begin(9600); // open the serial port at 9600 bps:
}
void loop() {
// print labels
Serial.print("NO FORMAT"); // prints a label
Serial.print("\t"); // prints a tab
Serial.print("DEC");
Serial.print("\t");
Serial.print("HEX");
Serial.print("\t");
Serial.print("OCT");
Serial.print("\t");
Serial.print("BIN");
Serial.println(); // carriage return after the last label
for (int x = 0; x < 64; x++) { // only part of the ASCII chart,
change to suit
// print it out in many formats:
Serial.print(x); // print as an ASCII-encoded decimal -
same as "DEC"
Serial.print("\t\t"); // prints two tabs to accomodate the
label lenght
Serial.println()
Syntax
Serial.println(val)
Serial.println(val, format)
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
val: the value to print. Allowed data types: any data type.
format: specifies the number base (for integral data types) or
number of decimal places (for floating point types).
Returns
Example Code
/*
Analog input reads an analog input on analog in 0, prints the
value out.
created 24 March 2006
by Tom Igoe
*/
void setup() {
// open the serial port at 9600 bps:
Serial.begin(9600);
}
void loop() {
// read the analog input on pin 0:
analogValue = analogRead(0);
Description
Syntax
Serial.read()
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
Returns
Example Code
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600
bps
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
Description
Syntax
Serial.readBytes(buffer, length)
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
buffer: the buffer to store the bytes in. Allowed data types: array
of char or byte.
length: the number of bytes to read. Allowed data types: int.
Returns
Description
Syntax
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
character: the character to search for. Allowed data types: char.
buffer: the buffer to store the bytes in. Allowed data types: array
of char or byte.
length: the number of bytes to read. Allowed data types: int.
Returns
Serial.readString()
Description
Syntax
Serial.readString()
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
Returns
Example Code
Demonstrate Serial.readString()
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("Enter data:");
while (Serial.available() == 0) {} //wait for data available
String teststr = Serial.readString(); //read until timeout
teststr.trim(); // remove any \r \n
whitespace at the end of the String
if (teststr == "red") {
Serial.println("A primary color");
} else {
Serial.println("Something else");
}
}
The function does not terminate early if the data contains end of line
characters. The returned String may contain carriage return and/or
line feed characters if they were received.
Serial.readStringUntil()
Description
Syntax
Serial.readStringUntil(terminator)
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
terminator: the character to search for. Allowed data types: char.
Returns
The entire String read from the serial buffer, up to the terminator
character
Serial.setTimeout()
Description
Syntax
Serial.setTimeout(time)
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
time: timeout duration in milliseconds. Allowed data types: long.
Returns
Nothing
Notes and Warnings
Serial.find()
Serial.findUntil()
Serial.parseInt()
Serial.parseFloat()
Serial.readBytes()
Serial.readBytesUntil()
Serial.readString()
Serial.readStringUntil()
Serial.write()
Description
Writes binary data to the serial port. This data is sent as a byte or
series of bytes; to send the characters representing the digits of a
number use the print() function instead.
Syntax
Serial.write(val)
Serial.write(str)
Serial.write(buf, len)
Parameters
Serial: serial port object. See the list of available serial ports for each
board on the Serial main page.
val: a value to send as a single byte.
str: a string to send as a series of bytes.
buf: an array to send as a series of bytes.
len: the number of bytes to be sent from the array.
Returns
write() will return the number of bytes written, though reading that
number is optional. Data type: size_t.
Example Code
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.write(45); // send a byte with the value 45
serialEvent()
For boards with additional serial ports (see the list of available serial
ports for each board on the Serial main page):
void serialEvent1() {
//statements
}
void serialEvent2() {
//statements
}
void serialEvent3() {
//statements
}
Parameters
Returns
Nothing
Description
This library allows you to communicate with SPI devices, with the
Arduino as the controller device. This library is bundled with every
Arduino platform (avr, megaavr, mbed, samd, sam, arc32), so you
do not need to install the library separately.
#include <SPI.h>
To read more about Arduino and SPI, you can visit the Arduino &
Serial Peripheral Interface (SPI) guide.
Functions
SPISettings
begin()
beginTransaction()
endTransaction()
end()
setBitOrder()
setClockDivider()
setDataMode()
transfer()
usingInterrupt()
Arduino & Serial Peripheral Interface (SPI)
Serial Peripheral Interface (SPI) is a synchronous serial data protocol used by
microcontrollers for communicating with one or more peripheral devices quickly over
short distances.
SPI Library
The SPI Library is included in every Arduino core/platform, so you
do not need to install it externally. You can read more about SPI
functions in the links below:
SPI Library
GitHub (ArduinoCore-avr)
CIPO (Controller In Peripheral Out) - The Peripheral line for sending data to
the Controller
COPI (Controller Out Peripheral In) - The Controller line for sending data to
the peripherals
SCK (Serial Clock) - The clock pulses which synchronize data transmission
generated by the Controller and one line specific for every device
CS (Chip Select) - the pin on each device that the Controller can use to enable
and disable specific devices. When a device's Chip Select pin is low, it
communicates with the Controller. When it's high, it ignores the Controller. This
allows you to have multiple SPI devices sharing the same CIPO, COPI, and
SCK lines.
To write code for a new SPI device you need to note a few things:
What is the maximum SPI speed your device can use? This is controlled by the
first parameter in SPISettings. If you are using a chip rated at 15 MHz, use
15000000. Arduino will automatically use the best speed that is equal to or less
than the number you use with SPISettings.
Is data shifted in Most Significant Bit (MSB) or Least Significant Bit (LSB) first?
This is controlled by second SPISettings parameter, either MSBFIRST or
LSBFIRST. Most SPI chips use MSB first data order.
Is the data clock idle when high or low? Are samples on the rising or falling
edge of clock pulses? These modes are controlled by the third parameter in
SPISettings.
The SPI standard is loose and each device implements it a little differently. This
means you have to pay special attention to the device's datasheet when writing
your code.
SPI.beginTransaction()
. For example:
COPY
SPI.endTransaction()
doesn't change SPI settings. Unless you, or some library, calls beginTransaction a second time,
the setting are maintained. You should attempt to minimize the time between before you call
SPI.endTransaction()
, for best compatibility if your program is used together with other libraries which use SPI.
SPI.transfer()
any number of times to transfer data, then write the CS pin HIGH, and finally call
SPI.endTransaction()
.
Tutorials
Extended SPI Library Usage with the Arduino Due
Introduction to the Serial Peripheral Interface
Digital Potentiometer Control (SPI)
Barometric Pressure Sensor (SPI)
SPI Functions
SPISettings
The SPISettings object is used to configure the SPI port for your SPI
device. All 3 parameters are combined to a single SPISettings object,
which is given to SPI.beginTransaction().
If any of your settings are variables, you may create a SPISettings object
to hold the 3 settings. Then you can give the object name to
SPI.beginTransaction(). Creating a named SPISettings object may be more
efficient when your settings are not constants, especially if the maximum
speed is a variable computed or configured, rather than a number you
type directly into your sketch.
Syntax
SPI.beginTransaction(SPISettings(14000000, MSBFIRST,
SPI_MODE0)) Note: Best if all 3 settings are constants
Parameters
Returns: none
SPI.begin()
Initializes the SPI bus by setting SCK, MOSI, and SS to outputs,
pulling SCK and MOSI low, and SS high.
Syntax
SPI.begin()
Parameters
None.
Returns
None.
SPI.beginTransaction()
Syntax
SPI.beginTransaction(mySettings)
Parameters
Returns
None.
SPI.endTransaction()
Stop using the SPI bus. Normally this is called after de-asserting the
chip select, to allow other libraries to use the SPI bus.
Syntax
SPI.endTransaction()
Parameters
None.
Returns
None.
SPI.end()
Syntax
SPI.end()
Parameters
None.
Returns
None.
SPI.setClockDivider()
Description
Sets the SPI clock divider relative to the system clock. On AVR
based boards, the dividers available are 2, 4, 8, 16, 32, 64 or 128.
The default setting is SPI_CLOCK_DIV4, which sets the SPI clock to
one-quarter the frequency of the system clock (4 Mhz for the boards
at 16 MHz).
For Arduino Due: On the Due, the system clock can be divided by
values from 1 to 255. The default value is 21, which sets the clock
to 4 MHz like other Arduino boards.
Syntax
SPI.setClockDivider(divider)
Parameters
SPI_CLOCK_DIV2
SPI_CLOCK_DIV4
SPI_CLOCK_DIV8
SPI_CLOCK_DIV16
SPI_CLOCK_DIV32
SPI_CLOCK_DIV64
SPI_CLOCK_DIV128
chipSelectPin: peripheral device CS pin (Arduino Due
only) divider: a number from 1 to 255 (Arduino Due only)
Returns
None.
SPI.setBitOrder()
Sets the order of the bits shifted out of and into the SPI bus, either
LSBFIRST (least-significant bit first) or MSBFIRST (most-significant
bit first).
Syntax
SPI.setBitOrder(order)
Parameters
Returns
None.
SPI.setDataMode()
Description
Sets the SPI data mode: that is, clock polarity and phase. See the
Wikipedia article on SPI for details.
Syntax
SPI.setDataMode(mode)
Parameters
mode:
SPI_MODE0
SPI_MODE1
SPI_MODE2
SPI_MODE3
Returns
None.
SPI.transfer()
Description
Syntax
receivedVal = SPI.transfer(val)
receivedVal16 = SPI.transfer16(val16)
SPI.transfer(buffer, size)
Parameters
val16: the two bytes variable to send out over the bus
Returns
Description
Syntax
SPI.usingInterrupt(interruptNumber)
Parameters
Returns
None.
Stream
[Communication]
Stream is the base class for character and binary based streams. It
is not called directly, but invoked whenever you use a function that
relies on it.
Serial
Wire
Ethernet
SD
Functions
available()
read()
flush()
find()
findUntil()
peek()
readBytes()
readBytesUntil()
readString()
readStringUntil()
parseInt()
parseFloat()
setTimeout()
Stream functions
Stream.available()
This function is part of the Stream class, and can be called by any
class that inherits from it (Wire, Serial, etc). See the Stream
class main page for more information.
Syntax
stream.available()
Parameters
Returns
Stream.read()
This function is part of the Stream class, and can be called by any
class that inherits from it (Wire, Serial, etc). See the stream
class main page for more information.
Syntax
stream.read()
Parameters
Returns
Stream.flush()
flush() clears the buffer once all outgoing characters have been
sent.
This function is part of the Stream class, and can be called by any
class that inherits from it (Wire, Serial, etc). See the stream
class main page for more information.
Syntax
stream.flush()
Parameters
Returns
Nothing
Stream.find()
find() reads data from the stream until the target is found. The
function returns true if target is found, false if timed out
(see Stream.setTimeout()).
This function is part of the Stream class, and can be called by any
class that inherits from it (Wire, Serial, etc). See the stream
class main page for more information.
Syntax
stream.find(target)
stream.find(target, length)
Parameters
Returns
Stream.findUntil()
findUntil() reads data from the stream until the target string of
given length or terminator string is found, or it times out
(see Stream.setTimeout()).
The function returns true if target string is found, false if timed out.
This function is part of the Stream class, and can be called by any
class that inherits from it (Wire, Serial, etc). See the Stream
class main page for more information.
Syntax
stream.findUntil(target, terminal)
Parameters
Returns
Stream.peek()
Read a byte from the file without advancing to the next one. That is,
successive calls to peek() will return the same value, as will the next
call to read().
This function is part of the Stream class, and can be called by any
class that inherits from it (Wire, Serial, etc). See the Stream
class main page for more information.
Syntax
stream.peek()
Parameters
Returns
Stream.readBytes()
This function is part of the Stream class, and can be called by any
class that inherits from it (Wire, Serial, etc). See the Stream
class main page for more information.
Syntax
stream.readBytes(buffer, length)
Parameters
Returns
This function is part of the Stream class, and can be called by any
class that inherits from it (Wire, Serial, etc). See the Stream
class main page for more information.
Syntax
Parameters
Returns
This function is part of the Stream class, and can be called by any
class that inherits from it (Wire, Serial, etc). See the Stream
class main page for more information.
Syntax
stream.readString()
Parameters
Returns
Stream.readStringUntil()
This function is part of the Stream class, and can be called by any
class that inherits from it (Wire, Serial, etc). See the Stream
class main page for more information.
Syntax
stream.readStringUntil(terminator)
Parameters
Returns
Stream.parseInt()
parseInt() returns the first valid (long) integer number from the
current position.
In particular:
This function is part of the Stream class, and can be called by any
class that inherits from it (Wire, Serial, etc). See the Stream
class main page for more information.
Syntax
stream.parseInt()
stream.parseInt(lookahead)
stream.parseInt(lookahead, ignore)
Parameters
SKIP_ALL: all characters other than digits or a minus sign are ignored
when scanning the stream for an integer. This is the default mode.
ignore: used to skip the indicated char in the search. Used for
example to skip thousands divider. Allowed data types: char
Returns
Stream.parseFloat()
parseFloat() returns the first valid floating point number from the
current position. parseFloat() is terminated by the first character
that is not a floating point number. The function terminates if it
times out (see Stream.setTimeout()).
This function is part of the Stream class, and can be called by any
class that inherits from it (Wire, Serial, etc). See the Stream
class main page for more information.
Syntax
stream.parseFloat()
stream.parseFloat(lookahead)
stream.parseFloat(lookahead, ignore)
Parameters
ignore: used to skip the indicated char in the search. Used for
example to skip thousands divider. Allowed data types: char
Returns
Stream.setTimeout()
stream.setTimeout(time)
Parameters
Returns
Nothing
Stream functions that use the timeout value set via setTimeout():
find()
findUntil()
parseInt()
parseFloat()
readBytes()
readBytesUntil()
readString()
readStringUntil()
As a reference the table below shows where TWI pins are located on
various Arduino boards.
Note: There are both 7 and 8-bit versions of I2C addresses. 7 bits
identify the device, and the eighth bit determines if it’s being written
to or read from. The Wire library uses 7 bit addresses throughout. If
you have a datasheet or sample code that uses 8-bit address, you’ll
want to drop the low bit (i.e. shift the value one bit to the right),
yielding an address between 0 and 127. However the addresses
from 0 to 7 are not used because are reserved so the first address
that can be used is 8. Please note that a pull-up resistor is needed
when connecting SDA/SCL pins. Please refer to the examples for
more information. MEGA 2560 board has pull-up resistors on pins 20
and 21 onboard.
#include <Wire.h>
Functions
begin()
end()
requestFrom()
beginTransmission()
endTransmission()
write()
available()
read()
setClock()
onReceive()
onRequest()
setWireTimeout()
clearWireTimeoutFlag()
getWireTimeoutFlag()
Wire functions
begin()
This function initializes the Wire library and join the I2C bus as a
controller or a peripheral. This function should normally be called
only once.
Syntax
Wire.begin()
Wire.begin(address)
Parameters
address: the 7-bit slave address (optional); if not specified, join the
bus as a controller device.
Returns
None.
end()
Note: This function was not available in the original version of the
Wire library and might still not be available on all platforms. Code
that needs to be portable across platforms and versions can use
the WIRE_HAS_END macro, which is only defined when Wire.end() is
available.
Syntax
Wire.end()
Parameters
None.
Returns
None.
requestFrom()
Syntax
Wire.requestFrom(address, quantity)
Parameters
address: the 7-bit slave address of the device to request bytes from.
quantity: the number of bytes to request.
stop: true or false. true will send a stop message after the request,
releasing the bus. False will continually send a restart after the
request, keeping the connection active.
Returns
beginTransmission()
Syntax
Wire.beginTransmission(address)
Parameters
Returns
None.
endTransmission()
Syntax
Wire.endTransmission() Wire.endTransmission(stop)
Parameters
stop: true or false. True will send a stop message, releasing the bus
after transmission. False will send a restart, keeping the connection
active.
Returns
0: success.
4: other error.
5: timeout
write()
Syntax
Parameters
Returns
Example
#include <Wire.h>
byte val = 0;
void setup() {
Wire.begin(); // Join I2C bus
}
void loop() {
Wire.beginTransmission(44); // Transmit to device number 44
(0x2C)
delay(500);
}
available()
Syntax
Wire.available()
Parameters
None.
Returns
read()
Syntax
Wire.read()
Parameters
None.
Returns
Example
#include <Wire.h>
void setup() {
Wire.begin(); // Join I2C bus (address is optional
for controller device)
Serial.begin(9600); // Start serial for output
}
void loop() {
Wire.requestFrom(2, 6); // Request 6 bytes from slave device
number two
delay(500);
}
setClock()
Syntax
Wire.setClock(clockFrequency)
Parameters
Returns
None.
onReceive()
Syntax
Wire.onReceive(handler)
Parameters
Returns
None.
onRequest()
Syntax
Wire.onRequest(handler)
Parameters
Returns
None.
setWireTimeout()
Syntax
Wire.setWireTimeout(timeout, reset_on_timeout)
Wire.setWireTimeout()
Parameters
Returns
None.
Example Code
#include <Wire.h>
void setup() {
Wire.begin(); // join i2c bus (address optional for master)
#if defined(WIRE_HAS_TIMEOUT)
Wire.setWireTimeout(3000 /* us */, true /* reset_on_timeout
*/);
#endif
}
byte x = 0;
void loop() {
/* First, send a command to the other device */
Wire.beginTransmission(8); // transmit to device #8
Wire.write(123); // send command
byte error = Wire.endTransmission(); // run transaction
if (error) {
Serial.println("Error occured when writing");
if (error == 5)
Serial.println("It was a timeout");
}
delay(100);
delay(100);
}
Note that this timeout can also trigger while waiting for clock
stretching or waiting for a second master to complete its
transaction. So make sure to adapt the timeout to accomodate for
those cases if needed. A typical timeout would be 25ms (which is
the maximum clock stretching allowed by the SMBus protocol), but
(much) shorter values will usually also work.
Portability Notes
This function was not available in the original version of the Wire
library and might still not be available on all platforms. Code that
needs to be portable across platforms and versions can use
the WIRE_HAS_TIMEOUT macro, which is only defined
when Wire.setWireTimeout(), Wire.getWireTimeoutFlag() and Wire.cle
arWireTimeout() are all available.
Syntax
Wire.clearTimeout()
Parameters
None.
Returns
None.
Portability Notes
This function was not available in the original version of the Wire
library and might still not be available on all platforms. Code that
needs to be portable across platforms and versions can use
the WIRE_HAS_TIMEOUT macro, which is only defined
when Wire.setWireTimeout(), Wire.getWireTimeoutFlag() and Wire.cle
arWireTimeout() are all available.
getWireTimeoutFlag()
Checks whether a timeout has occured since the last time the flag
was cleared.
Syntax
Wire.getWireTimeoutFlag()
Parameters
None.
Returns
Portability Notes
This function was not available in the original version of the Wire
library and might still not be available on all platforms. Code that
needs to be portable across platforms and versions can use
the WIRE_HAS_TIMEOUT macro, which is only defined
when Wire.setWireTimeout(), Wire.getWireTimeoutFlag() and Wire.cle
arWireTimeout() are all available.
Keyboard
[USB]
These core libraries allow the 32u4 and SAMD based boards
(Leonardo, Esplora, Zero, Due and MKR Family) to appear as a
native Mouse and/or Keyboard to a connected computer.
Keyboard.begin()
Keyboard.end()
Keyboard.press()
Keyboard.print()
Keyboard.println()
Keyboard.release()
Keyboard.releaseAll()
Keyboard.write()
See also
Keyboard.begin()
Syntax
Keyboard.begin()
Keyboard.begin(layout)
Parameters
Keyboard layouts
KeyboardLayout_da_DK: Denmark
KeyboardLayout_de_DE: Germany
KeyboardLayout_en_US: USA
KeyboardLayout_es_ES: Spain
KeyboardLayout_fr_FR: France
KeyboardLayout_hu_HU: Hungary
KeyboardLayout_it_IT: Italy
KeyboardLayout_pt_PT: Portugal
KeyboardLayout_sv_SE: Sweden
Returns
Nothing
Example Code
#include <Keyboard.h>
void setup() {
// make pin 2 an input and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}
void loop() {
//if the button is pressed
if (digitalRead(2) == LOW) {
//Send the message
Keyboard.print("Hello!");
}
}
Keyboard.end()
Syntax
Keyboard.end()
Parameters
None
Returns
Nothing
Example Code
#include <Keyboard.h>
void setup() {
//start keyboard communication
Keyboard.begin();
//send a keystroke
Keyboard.print("Hello!");
//end keyboard communication
Keyboard.end();
}
void loop() {
//do nothing
}
Keyboard.press()
Syntax
Keyboard.press(key)
Parameters
Returns
void setup() {
// make pin 2 an input and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
// initialize control over the keyboard:
Keyboard.begin();
}
void loop() {
while (digitalRead(2) == HIGH) {
// do nothing until pin 2 goes low
delay(500);
}
delay(1000);
// new document:
Keyboard.press(ctrlKey);
Keyboard.press('n');
delay(100);
Keyboard.releaseAll();
// wait for new window to open:
delay(1000);
}
Keyboard.print()
Syntax
Keyboard.print(character)
Keyboard.print(characters)
Parameters
Example Code
#include <Keyboard.h>
void setup() {
// make pin 2 an input and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}
void loop() {
//if the button is pressed
if (digitalRead(2) == LOW) {
//Send the message
Keyboard.print("Hello!");
}
}
Keyboard.println()
Keyboard.println()
Keyboard.println(character)
Keyboard.println(characters)
Parameters
Returns
Example Code
#include <Keyboard.h>
void setup() {
// make pin 2 an input and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}
void loop() {
//if the button is pressed
if (digitalRead(2) == LOW) {
//Send the message
Keyboard.println("Hello!");
}
}
Syntax
Keyboard.release(key)
Parameters
Returns
#include <Keyboard.h>
void setup() {
// make pin 2 an input and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
// initialize control over the keyboard:
Keyboard.begin();
}
void loop() {
while (digitalRead(2) == HIGH) {
// do nothing until pin 2 goes low
delay(500);
}
delay(1000);
// new document:
Keyboard.press(ctrlKey);
Keyboard.press('n');
delay(100);
Keyboard.release(ctrlKey);
Keyboard.release('n');
// wait for new window to open:
delay(1000);
}
Keyboard.releaseAll()
Syntax
Keyboard.releaseAll()
Parameters
None
Returns
Nothing
#include <Keyboard.h>
void setup() {
// make pin 2 an input and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
// initialize control over the keyboard:
Keyboard.begin();
}
void loop() {
while (digitalRead(2) == HIGH) {
// do nothing until pin 2 goes low
delay(500);
}
delay(1000);
// new document:
Keyboard.press(ctrlKey);
Keyboard.press('n');
delay(100);
Keyboard.releaseAll();
// wait for new window to open:
delay(1000);
}
Keyboard.write()
Only ASCII characters that are on the keyboard are supported. For
example, ASCII 8 (backspace) would work, but ASCII 25
(Substitution) would not. When sending capital
letters, Keyboard.write() sends a shift command plus the desired
character, just as if typing on a keyboard. If sending a numeric type,
it sends it as an ASCII character (ex. Keyboard.write(97) will send
'a').
Syntax
Keyboard.write(character)
Parameters
Returns
void setup() {
// make pin 2 an input and turn on the
// pullup resistor so it goes high unless
// connected to ground:
pinMode(2, INPUT_PULLUP);
Keyboard.begin();
}
void loop() {
//if the button is pressed
if (digitalRead(2) == LOW) {
//Send an ASCII 'A',
Keyboard.write(65);
}
Mouse
[USB]
These core libraries allow the 32u4 and SAMD based boards
(Leonardo, Esplora, Zero, Due and MKR Family) to appear as a
native Mouse and/or Keyboard to a connected computer.
Functions
Mouse.begin()
Mouse.click()
Mouse.end()
Mouse.move()
Mouse.press()
Mouse.release()
Mouse.isPressed()
See also
Mouse.begin()
Syntax
Mouse.begin()
Parameters
None
Returns
Nothing
Example Code
#include <Mouse.h>
void setup() {
pinMode(2, INPUT);
}
void loop() {
//initiate the Mouse library when button is pressed
if (digitalRead(2) == HIGH) {
Mouse.begin();
}
}
Mouse.click()
Syntax
Mouse.click()
Mouse.click(button)
Parameters
MOUSE_LEFT (default)
MOUSE_RIGHT
MOUSE_MIDDLE
Returns
Nothing
#include <Mouse.h>
void setup() {
pinMode(2, INPUT);
//initiate the Mouse library
Mouse.begin();
}
void loop() {
//if the button is pressed, send a left mouse click
if (digitalRead(2) == HIGH) {
Mouse.click();
}
}
When you use the Mouse.click() command, the Arduino takes over
your mouse! Make sure you have control before you use the
command. A pushbutton to toggle the mouse control state is
effective.
Mouse.end()
Syntax
Mouse.end()
Parameters
None
Returns
Nothing
#include <Mouse.h>
void setup() {
pinMode(2, INPUT);
//initiate the Mouse library
Mouse.begin();
}
void loop() {
//if the button is pressed, send a left mouse click
//then end the Mouse emulation
if (digitalRead(2) == HIGH) {
Mouse.click();
Mouse.end();
}
}
Mouse.move()
Parameters
xVal: amount to move along the x-axis. Allowed data types: signed
char.
yVal: amount to move along the y-axis. Allowed data types: signed
char.
wheel: amount to move scroll wheel. Allowed data types: signed
char.
Returns
Nothing
Example Code
#include <Mouse.h>
void setup() {
Mouse.begin();
}
void loop() {
// read and scale the two axes:
int xReading = readAxis(0);
int yReading = readAxis(1);
/*
reads an axis (0 or 1 for x or y) and scales the
analog input range to a range from 0 to <range>
*/
// of the current reading exceeds the max or min for this axis,
// reset the max or min:
if (reading < minima[axisNumber]) {
minima[axisNumber] = reading;
}
if (reading > maxima[axisNumber]) {
maxima[axisNumber] = reading;
}
// map the reading from the analog input range to the output
range:
reading = map(reading, minima[axisNumber], maxima[axisNumber], 0,
range);
When you use the Mouse.move() command, the Arduino takes over
your mouse! Make sure you have control before you use the
command. A pushbutton to toggle the mouse control state is
effective.
Mouse.press()
Syntax
Mouse.press()
Mouse.press(button)
Parameters
MOUSE_LEFT (default)
MOUSE_RIGHT
MOUSE_MIDDLE
Returns
Nothing
Example Code
#include <Mouse.h>
void setup() {
//The switch that will initiate the Mouse press
pinMode(2, INPUT);
//The switch that will terminate the Mouse press
pinMode(3, INPUT);
//initiate the Mouse library
Mouse.begin();
}
void loop() {
//if the switch attached to pin 2 is closed, press and hold the
left mouse button
if (digitalRead(2) == HIGH) {
Mouse.press();
}
//if the switch attached to pin 3 is closed, release the left
mouse button
if (digitalRead(3) == HIGH) {
Mouse.release();
}
}
When you use the Mouse.press() command, the Arduino takes over
your mouse! Make sure you have control before you use the
command. A pushbutton to toggle the mouse control state is
effective.
Mouse.release()
Syntax
Mouse.release()
Mouse.release(button)
Parameters
MOUSE_LEFT (default)
MOUSE_RIGHT
MOUSE_MIDDLE
Returns
Nothing
Example Code
#include <Mouse.h>
void setup() {
//The switch that will initiate the Mouse press
pinMode(2, INPUT);
//The switch that will terminate the Mouse press
pinMode(3, INPUT);
//initiate the Mouse library
Mouse.begin();
}
void loop() {
//if the switch attached to pin 2 is closed, press and hold the
left mouse button
if (digitalRead(2) == HIGH) {
Mouse.press();
}
//if the switch attached to pin 3 is closed, release the left
mouse button
if (digitalRead(3) == HIGH) {
Mouse.release();
}
}
When you use the Mouse.release() command, the Arduino takes over
your mouse! Make sure you have control before you use the
command. A pushbutton to toggle the mouse control state is
effective.
Mouse.isPressed()
Checks the current status of all mouse buttons, and reports if any
are pressed or not.
Syntax
Mouse.isPressed();
Mouse.isPressed(button);
Parameters
MOUSE_LEFT (default)
MOUSE_RIGHT
MOUSE_MIDDLE
Returns
Example Code
#include <Mouse.h>
void setup() {
//The switch that will initiate the Mouse press
pinMode(2, INPUT);
//The switch that will terminate the Mouse press
pinMode(3, INPUT);
//Start serial communication with the computer
Serial.begin(9600);
//initiate the Mouse library
Mouse.begin();
}
void loop() {
//a variable for checking the button's state
int mouseState = 0;
//if the switch attached to pin 2 is closed, press and hold the
left mouse button and save the state ina variable
if (digitalRead(2) == HIGH) {
Mouse.press();
mouseState = Mouse.isPressed();
}
//if the switch attached to pin 3 is closed, release the left
mouse button and save the state in a variable
if (digitalRead(3) == HIGH) {
Mouse.release();
mouseState = Mouse.isPressed();
}
//print out the current mouse button state
Serial.println(mouseState);
delay(10);
}
Part 2: Values (pages 174 - 243)
Arduino data types and constants.
Constants
HIGH | LOW
INPUT | OUTPUT | INPUT_PULLUP
LED_BUILTIN
true | false
Floating Point Constants
Integer Constants
Conversion
(unsigned int)
(unsigned long)
byte()
char()
float()
int()
long()
word()
Data Types
array
bool
boolean
byte
char
double
float
int
long
short
size_t
string
String()
unsigned char
unsigned int
unsigned long
void
word
Utilities
PROGMEM
sizeof()
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:
There are two constants used to represent truth and falsity in the
Arduino language: true, and false.
false
true
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
a voltage less than 1.0V (Approx) is present at the pin (3.3V boards)
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.
See the Input Pullup Serial tutorial for an example of this in use.
(unsigned int)
[Conversion]
Syntax
(unsigned int)x
Parameters
Returns
unsigned int
(unsigned long)
[Conversion]
Syntax
(unsigned long)x
Parameters
Returns
unsigned long
byte()
[Conversion]
Syntax
byte(x)
(byte)x (C-style type conversion)
Parameters
Returns
char()
[Conversion]
Syntax
char(x)
(char)x (C-style type conversion)
Parameters
Returns
Syntax
float(x)
(float)x (C-style type conversion)
Parameters
Returns
See the reference for float for details about the precision and
limitations of floating point numbers on Arduino.
int()
[Conversion]
Syntax
int(x)
(int)x (C-style type conversion)
Parameters
Returns
long()
[Conversion]
Syntax
long(x)
(long)x (C-style type conversion)
Parameters
Returns
word()
[Conversion]
word(x)
word(h, l)
(word)x (C-style type conversion)
Parameters
Returns
array
[Data Types]
All of the methods below are valid ways to create (declare) 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
It also means that in an array with ten elements, index nine is the
last element. Hence:
mySensVals[0] = 10;
x = mySensVals[4];
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:
This variation on the For Loop Iteration example shows how to use
an array. An array is a variable with multiple parts. If you think of a
variable as a cup that holds values, you might think of an array as
an ice cube tray. It's like a series of linked cups, all of which can
hold the same maximum value.
The For Loop Iteration example shows you how to light up a series
of LEDs attached to pins 2 through 7 of the Arduino board, with
certain limitations (the pins have to be numbered contiguously, and
the LEDs have to be turned on in sequence).
This example shows you how you can turn on a sequence of pins
whose numbers are neither contiguous nor necessarily sequential.
To do this is, you can put the pin numbers in an array and then
use for loops to iterate over the array.
Hardware Required
Arduino Board
6 LEDs
breadboard
Circuit
Connect six LEDs, with 220 ohm resistors in series, to digital pins 2-
7 on your board.
/*
Arrays
Demonstrates the use of an array to hold pin numbers in order to iterate over
Unlike the For Loop tutorial, where the pins have to be contiguous, here the
https://www.arduino.cc/en/Tutorial/Array
*/
int timer = 100; // The higher the number, the slower the timing.
int ledPins[] = {
int pinCount = 6; // the number of pins (i.e. the length of the array)
void setup() {
pinMode(ledPins[thisPin], OUTPUT);
void loop() {
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
digitalWrite(ledPins[thisPin], LOW);
bool
[Data Types]
A bool holds one of two values, true or false. (Each bool variable
occupies one byte of memory.)
Syntax
Parameters
Example Code
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
boolean
[Data Types]
byte
[Data Types]
Syntax
Parameters
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.
Syntax
Parameters
Example Code
char myChar = 'A';
char myChar = 65; // both are equivalent
double
[Data Types]
Syntax
Parameters
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.
float
[Data Types]
Parameters
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)
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.
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
float x = 2.9;
int y = round(x); // 3
int
[Data Types]
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).
Syntax
Parameters
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.
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);
}
long
[Data Types]
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.
Syntax
Parameters
Example Code
long speedOfLight_km_s = 300000L; // see the Integer Constants
page for explanation of the 'L'
short
[Data Types]
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
Parameters
Example Code
short ledPin = 13
size_t
[Data Types]
Syntax
Parameters
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
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 Str5[8] = "arduino";
char Str6[15] = "arduino";
Declare an array of chars (with one extra char) and the compiler will
add the required null character, as in Str2
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.
Arrays of strings
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
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);
}
}
String()
[Data Types]
gives you the String "13". You can use other bases, however. For
example,
Syntax
String(val)
String(val, base)
String(val, decimalPlaces)
Parameters
Example Code
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 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 + (concatenation)
LANGUAGE += (append)
LANGUAGE == (comparison)
charAt()
[StringObject Function]
Syntax
myString.charAt(n)
Parameters
Returns
compareTo()
[StringObject Function]
Syntax
myString.compareTo(myString2)
Parameters
Returns
concat()
[StringObject Function]
Syntax
myString.concat(parameter)
Parameters
Returns
true: success.
false: failure (in which case the String is left unchanged).
c_str()
[StringObject Function]
Syntax
myString.c_str()
Parameters
Returns
endsWith()
[StringObject Function]
Syntax
myString.endsWith(myString2)
Parameters
Returns
equals()
[StringObject Function]
Syntax
myString.equals(myString2)
Parameters
Returns
Syntax
myString.equalsIgnoreCase(myString2)
Parameters
Returns
getBytes()
[StringObject Function]
Syntax
myString.getBytes(buf, len)
Parameters
Returns
Nothing
indexOf()
[StringObject Function]
Syntax
myString.indexOf(val)
myString.indexOf(val, from)
Parameters
Returns
Syntax
myString.lastIndexOf(val)
myString.lastIndexOf(val, from)
Parameters
Returns
length()
[StringObject Function]
Syntax
myString.length()
Parameters
Returns
remove()
[StringObject Function]
Syntax
myString.remove(index)
myString.remove(index, count)
Parameters
Returns
Nothing
Example Code
String greeting = "hello";
greeting.remove(2, 2); // greeting now contains "heo"
replace()
[StringObject Function]
Syntax
myString.replace(substring1, substring2)
Parameters
Returns
Nothing
reserve()
[StringObject Function]
Syntax
myString.reserve(size)
Parameters
Returns
Nothing
Example Code
String myString;
void setup() {
// initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB
}
myString.reserve(26);
myString = "i=";
myString += "1234";
myString += ", is that ok?";
void loop() {
// nothing to do here
setCharAt()
[StringObject Function]
Syntax
myString.setCharAt(index, c)
Parameters
Returns
Nothing
startsWith()
[StringObject Function]
Syntax
myString.startsWith(myString2)
Parameters
Returns
Syntax
myString.substring(from)
myString.substring(from, to)
Parameters
Returns
The substring.
See also
toCharArray()
[StringObject Function]
Syntax
myString.toCharArray(buf, len)
Parameters
Returns
Nothing
toDouble()
[StringObject Function]
Syntax
myString.toDouble()
Parameters
Returns
Syntax
myString.toInt()
Parameters
Returns
toFloat()
[StringObject Function]
Converts a valid String to a float. The input String should start with
a digit. If the String contains non-digit characters, the function will
stop performing the conversion. For example, the Strings "123.45",
"123", and "123fish" are converted to 123.45, 123.00, and 123.00
respectively. Note that "123.456" is approximated with 123.46. Note
too that floats have only 6-7 decimal digits of precision and that
longer Strings might be truncated.
Syntax
myString.toFloat()
Parameters
Returns
toLowerCase()
[StringObject Function]
Syntax
myString.toLowerCase()
Parameters
Returns
Nothing
toUpperCase()
[StringObject Function]
myString.toUpperCase()
Parameters
Returns
Nothing
trim()
[StringObject Function]
Get a version of the String with any leading and trailing whitespace
removed. As of 1.0, trim() modifies the String in place rather than
returning a new one.
Syntax
myString.trim()
Parameters
Returns
Nothing
String() operators
[]
[StringObject Operator]
Syntax
Parameters
Returns
+
[StringObject Operator]
Syntax
Returns
+=
[StringObject Operator]
Syntax
myString1 += data
Parameters
Returns
Nothing
==
[StringObject Operator]
myString1 == myString2
Parameters
Returns
>
[StringObject Operator]
Tests if the String on the left is greater than the String on the right.
This operator evaluates Strings in alphabetical order, on the first
character where the two differ. So, for example "b" > "a" and "2" >
"1", but "999" > "1000" because 9 comes after 1.
Syntax
Returns
>=
[StringObject Operator]
Tests if the String on the left is greater than, or equal to, the String
on the right. This operator evaluate Strings in alphabetical order, on
the first character where the two differ. So, for example "b" >= "a"
and "2" >= "1", but "999" >= "1000" because 9 comes after 1.
Syntax
Parameters
<
[StringObject Operator]
Tests if the String on the left is less than the String on the right.
This operator evaluate Strings in alphabetical order, on the first
character where the two differ. So, for example "a" < "b" and "1" <
"2", but "999" > "1000" because 9 comes after 1.
Syntax
Parameters
Returns
Tests if the String on the left is less than or equal to the String on
the right. This operator evaluate Strings in alphabetical order, on
the first character where the two differ. So, for example "a" < "b"
and "1" < "2", but "999" > "1000" because 9 comes after 1.
Syntax
myString1 ⇐ myString2
Parameters
Returns
Syntax
Parameters
Example Code
unsigned char myChar = 240;
unsigned int
[Data Types]
Syntax
Parameters
Example Code
unsigned int ledPin = 13;
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
unsigned int x = 5;
unsigned int y = 10;
int result;
The signed variable is a bit too small, but you want to avoid the
memory and speed loss of long/float.
unsigned long
[Data Types]
Syntax
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);
}
void
[Data Types]
Example Code
void setup() {
// ...
}
void loop() {
// ...
}
word
[Data Types]
Syntax
Parameters
Example Code
word w = 10000;
const
[Variable Scope & Qualifiers]
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
#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.
scope
[Variable Scope & Qualifiers]
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.
Example Code
int gPWMval; // any function will see this variable
void setup() {
// ...
}
void loop() {
int i; // "i" is only "visible" inside of "loop"
float f; // "f" is only "visible" inside of "loop"
// ...
static
[Variable Scope & Qualifiers]
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".
*/
int thisTime;
void setup() {
Serial.begin(9600);
}
void loop() {
// test randomWalk function
stepsize = 5;
thisTime = randomWalk(stepsize);
Serial.println(thisTime);
delay(10);
}
return place;
}
volatile
[Variable Scope & Qualifiers]
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:
1. LANGUAGE noInterrupts
2. use the ATOMIC_BLOCK macro. Atomic operations are single MCU operations -
the smallest possible unit.
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.
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;
void toggle() {
changed = 1;
}
PROGMEM
[Utilities]
Syntax
Parameters
Example Code
void setup() {
Serial.begin(9600);
while (!Serial); // wait for serial port to connect. Needed for
native USB
Serial.println();
}
void loop() {
// put your main code here, to run repeatedly:
}
Arrays of strings
/*
PROGMEM string demo
How to store a table of strings in program memory (flash),
and retrieve them.
#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";
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. */
const char long_str[] PROGMEM = "Hi, I would like to tell you a bit
about myself.\n";
See also
DEFINITION array
DEFINITION string
sizeof()
[Utilities]
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
This program prints out a text string one character at a time. Try
changing the text phrase.
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.println();
}
delay(5000); // slow down the program
}
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.
// 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.
Sketch
loop()
setup()
Control Structure
break
continue
do...while
else
for
goto
if
return
switch...case
while
Further Syntax
#define (define)
#include (include)
/* */ (block comment)
// (single line comment)
; (semicolon)
{} (curly braces)
Arithmetic Operators
% (remainder)
* (multiplication)
+ (addition)
- (subtraction)
/ (division)
= (assignment operator)
Comparison Operators
!= (not equal to)
< (less than)
<= (less than or equal to)
== (equal to)
> (greater than)
>= (greater than or equal to)
Boolean Operators
! (logical not)
&& (logical and)
|| (logical or)
Bitwise Operators
& (bitwise and)
<< (bitshift left)
>> (bitshift right)
^ (bitwise xor)
| (bitwise or)
~ (bitwise not)
Compound Operators
%= (compound remainder)
&= (compound bitwise and)
*= (compound multiplication)
++ (increment)
+= (compound addition)
-- (decrement)
-= (compound subtraction)
/= (compound division)
^= (compound bitwise xor)
|= (compound bitwise or)
Sketch
loop()
[Sketch]
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
int buttonPin = 3;
delay(1000);
}
setup()
[Sketch]
Example Code
int buttonPin = 3;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
void loop() {
// ...
}
Control Structure
break
[Control Structure]
Example Code
In the following code, the control exits the for loop when the sensor
value exceeds the threshold.
continue
[Control Structure]
The following code writes the value of 0 to 255 to the PWMpin, but
skips the values in the range of 41 to 119.
analogWrite(PWMpin, x);
delay(50);
}
do...while
[Control Structure]
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
} while (condition);
Parameters
Example Code
// initialize x and i with a value of 0
int x = 0;
int i = 0;
do {
delay(50); // wait for sensors to stabilize
x = readSensors(); // check the sensors
i++; // increase i by 1
} while (i < 100); // repeat 100 times
else
[Control Structure]
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.
Syntax
if (condition1) {
// do Thing A
}
else if (condition2) {
// do Thing B
}
else {
// do Thing C
}
Example Code
Syntax
for (initialization; condition; increment) {
// statement(s);
}
Parameters
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
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.
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);
}
}
goto
[Control Structure]
Syntax
label:
bailout:
// more statements ...
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.
if
[Control Structure]
Syntax
if (condition) {
//statement(s)
}
Parameters
Example Code
if (x > 120)
digitalWrite(LEDpin, HIGH);
if (x > 120) {
digitalWrite(LEDpin1, HIGH);
digitalWrite(LEDpin2, HIGH);
}
// all are correct
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)
return
[Control Structure]
Syntax
return;
return value;
Parameters
Example Code
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;
switch...case
[Control Structure]
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
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;
}
while
[Control Structure]
Syntax
while (condition) {
// statement(s)
}
Parameters
Example Code
var = 0;
while (var < 200) {
// do something repetitive 200 times
var++;
}
Further Syntax
#define
[Further Syntax]
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).
Syntax
Parameters
Example Code
#define ledPin 3
// The compiler will replace any mention of ledPin with the value 3
at compile time.
#include
[Further Syntax]
Syntax
#include <LibraryFile.h>
#include "LocalFile.h"
Parameters
This example includes the Servo library so that its functions may be
used to control a Servo motor.
#include <Servo.h>
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo
object
}
void loop() {
for (int pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees
to 180 degrees
// in steps of 1 degree
myservo.write(pos); // tell servo to go to
position in variable 'pos'
delay(15); // waits 15ms for the servo to
reach the position
}
for (int pos = 180; pos >= 0; pos -= 1) { // goes from 180
degrees to 0 degrees
myservo.write(pos); // tell servo to go to
position in variable 'pos'
delay(15); // waits 15ms for the servo to
reach the position
}
}
/* */
[Further Syntax]
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 in the microcontroller’s flash memory. Comments' only
purpose is to help you understand (or remember), or to inform
others about how your program works.
Example Code
/* This is a valid comment */
/*
Blink
Turns on an LED on for one second, then off for one second,
repeatedly.
/*
if (gwb == 0) { // single line comment is OK inside a multi-line
comment
x = 3; /* but not another multi-line comment - this is
invalid */
}
// don't forget the "closing" comment - they have to be balanced!
*/
//
[Further Syntax]
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 in the microcontroller’s flash memory. Comments' only
purpose is to help you understand (or remember), or to inform
others about how your program works.
Example Code
;
[Further Syntax]
Example Code
int a = 13;
Notes and Warnings
{}
[Further Syntax]
Example Code
The main uses of curly braces are listed in the examples below.
Functions
void myfunction(datatype argument) {
// any statement(s)
}
Loops
while (boolean expression) {
// any statement(s)
}
do {
// any statement(s)
} while (boolean expression);
Conditional Statements
if (boolean expression) {
// any statement(s)
}
%
[Arithmetic Operators]
Syntax
Parameters
Example Code
int x = 0;
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
x = -4 % 5; // x now contains -4
x = 4 % -5; // x now contains 4
/* 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; // remainder operator rolls over variable
}
Notes and Warnings
2. If the first operand is negative, the result is negative (or zero). Therefore,
the result of x % 10 will not always be between 0 and 9 if x can be negative.
*
[Arithmetic Operators]
Syntax
Parameters
Example Code
int a = 5;
int b = 10;
int c = 0;
c = a * b; // the variable 'c' gets a value of 50 after this
statement is executed
1. The multiplication operation can overflow if the result is bigger than that
which can be stored in the data type.
2. If one of the numbers (operands) are of the type float or of type double,
floating point math will be used for the calculation.
3. If the operands are of float / double data type and the variable that stores the
product 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 36 only as
opposed to the expected product of 36.3
+
[Arithmetic Operators]
Syntax
Parameters
Example Code
int a = 5;
int b = 10;
int c = 0;
c = a + b; // the variable 'c' gets a value of 15 after this
statement is executed
Notes and Warnings
1. The addition operation can overflow if the result is larger than that which can
be stored in the data type (e.g. adding 1 to an integer with the value 32,767
gives -32,768).
2. If one of the numbers (operands) are of the type float or of type double,
floating point math will be used for the calculation.
3. If the operands are of float / double data type and the variable that stores the
sum 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 12 only as
opposed to the expected sum of 12.1
-
[Arithmetic Operators]
Syntax
Parameters
1. 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).
2. If one of the numbers (operands) are of the type float or of type double,
floating point math will be used for the calculation.
3. 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
/
[Arithmetic Operators]
Syntax
Parameters
Example Code
int a = 50;
int b = 10;
int c = 0;
c = a / b; // the variable 'c' gets a value of 5 after this
statement is executed
1. If one of the numbers (operands) are of the type float or of type double,
floating point math will be used for the calculation.
2. If the operands are of float / double data type and the variable that stores the
result is an integer, then only the integral part is stored and the fractional
part of the number is lost.
float a = 55.5;
float b = 6.6;
int c = 0;
c = a / b; // the variable 'c' stores a value of 8 only as opposed
to the expected result of 8.409
=
[Arithmetic Operators]
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 Code
int sensVal; // declare an integer variable named
sensVal
sensVal = analogRead(0); // store the (digitized) input voltage at
analog pin 0 in SensVal
Notes and Warnings
1. 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.
2. Don’t confuse the assignment operator [ = ] (single equal sign) with the
comparison operator [ == ] (double equal signs), which evaluates whether
two expressions are equal.
Comparison Operators
!=
[Comparison Operators]
Compares the variable on the left with the value or variable on the
right of the operator. Returns true when the two operands are not
equal. Please note that you may compare variables of different data
types, but that could generate unpredictable results, it is therefore
recommended to compare variables of the same data type including
the signed/unsigned type.
Syntax
Parameters
x: variable. Allowed data types: int, float, double, byte, short, long.
y: variable or constant. Allowed data
types: int, float, double, byte, short, long.
Example Code
if (x != y) { // tests if x is not equal to y
// do something only if the comparison result is true
}
<
[Comparison Operators]
Compares the variable on the left with the value or variable on the
right of the operator. Returns true when the operand on the left is
less (smaller) than the operand on the right. Please note that you
may compare variables of different data types, but that could
generate unpredictable results, it is therefore recommended to
compare variables of the same data type including the
signed/unsigned type.
Syntax
Parameters
x: variable. Allowed data types: int, float, double, byte, short, long.
y: variable or constant. Allowed data
types: int, float, double, byte, short, long.
Example Code
if (x < y) { // tests if x is less (smaller) than y
// do something only if the comparison result is true
}
Compares the variable on the left with the value or variable on the
right of the operator. Returns true when the operand on the left is
less (smaller) than or equal to the operand on the right. Please note
that you may compare variables of different data types, but that
could generate unpredictable results, it is therefore recommended to
compare variables of the same data type including the
signed/unsigned type.
Syntax
Parameters
x: variable. Allowed data types: int, float, double, byte, short, long.
y: variable or constant. Allowed data
types: int, float, double, byte, short, long.
Example Code
if (x <= y) { // tests if x is less (smaller) than or equal to y
// do something only if the comparison result is true
}
Compares the variable on the left with the value or variable on the
right of the operator. Returns true when the two operands are equal.
Please note that you may compare variables of different data types,
but that could generate unpredictable results, it is therefore
recommended to compare variables of the same data type including
the signed/unsigned type.
Syntax
Parameters
x: variable. Allowed data types: int, float, double, byte, short, long.
y: variable or constant. Allowed data
types: int, float, double, byte, short, long.
Example Code
if (x == y) { // tests if x is equal to y
// do something only if the comparison result is true
>
[Comparison Operators]
Compares the variable on the left with the value or variable on the
right of the operator. Returns true when the operand on the left is
greater (bigger) than the operand on the right. Please note that you
may compare variables of different data types, but that could
generate unpredictable results, it is therefore recommended to
compare variables of the same data type including the
signed/unsigned type.
Syntax
Parameters
x: variable. Allowed data types: int, float, double, byte, short, long.
y: variable or constant. Allowed data
types: int, float, double, byte, short, long.
Example Code
if (x > y) { // tests if x is greater (bigger) than y
// do something only if the comparison result is true
}
>=
[Comparison Operators]
Compares the variable on the left with the value or variable on the
right of the operator. Returns true when the operand on the left is
greater (bigger) than or equal to the operand on the right. Please
note that you may compare variables of different data types, but
that could generate unpredictable results, it is therefore
recommended to compare variables of the same data type including
the signed/unsigned type.
Syntax
x: variable. Allowed data types: int, float, double, byte, short, long.
y: variable or constant. Allowed data
types: int, float, double, byte, short, long.
Example Code
if (x >= y) { // tests if x is greater (bigger) than or equal to y
// do something only if the comparison result is true
}
Boolean Operators
!
[Boolean Operators]
Logical NOT results in a true if the operand is false and vice versa.
Example Code
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.
&&
[Boolean Operators]
Example Code
Make sure you don’t mistake the boolean AND operator, && (double
ampersand) for the bitwise AND operator & (single ampersand). They are
entirely different beasts.
||
[Boolean Operators]
Example Code
&
[Pointer Access Operators]
Example Code
int *p; // declare a pointer to an int data type
int i = 5;
int result = 0;
p = &i; // now 'p' contains the address of 'i'
result = *p; // 'result' gets the value at the address pointed by
'p'
// i.e., it gets the value of 'i' which is 5
Example Code
int *p; // declare a pointer to an int data type
int i = 5;
int result = 0;
p = &i; // now 'p' contains the address of 'i'
result = *p; // 'result' gets the value at the address pointed by
'p'
// i.e., it gets the value of 'i' which is 5
Bitwise Operators
&
[Bitwise Operators]
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
<<
[Bitwise Operators]
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
Parameters
Example Code
int a = 5; // binary: 0000000000000101
int b = a << 3; // binary: 0000000000101000, or 40 in decimal
When you shift a value x by y bits (x << y), the leftmost y bits in x
are lost, literally shifted out of existence:
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
...
>>
[Bitwise Operators]
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
Parameters
Example Code
int a = 40; // binary: 0000000000101000
int b = a >> 3; // binary: 0000000000000101, or 5 in decimal
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:
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:
Sign extension causes that you can use the right-shift operator >> as
a way to divide by powers of 2, even negative numbers. For
example:
int x = -1000;
int y = x >> 3; // integer division of -1000 by 8, causing y = -
125.
int x = -1001;
int y = x >> 3; // division by shifting always rounds down, causing
y = -126
int z = x / 8; // division operator rounds towards zero, causing z
= -125
^
[Bitwise Operators]
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
void loop() {
PORTB = PORTB ^ 0b00100000; // invert PB5, leave others
untouched
delay(100);
}
|
[Bitwise Operators]
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 c = a | b; // result: 0000000001111101, or 125 in decimal.
~
[Bitwise Operators]
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
At times, the sign bit in a signed integer expression can cause some
unwanted surprises.
Compound Operators
%=
[Compound Operators]
Syntax
Parameters
Example Code
int x = 7;
x %= 5; // x now contains 2
&=
[Compound Operators]
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.
0 0 1 1 operand1
0 1 0 1 operand2
----------
0 0 0 1 (operand1 & operand2) - returned result
Syntax
Parameters
Example Code
Bits that are "bitwise ANDed" with 0 are cleared to 0 so, if myByte is
a byte variable,
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
bits unchanged
bits cleared
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
bits unchanged
bits cleared
So if:
myByte = 0b10101010;
myByte &= 0b11111100; // results in 0b10101000
*=
[Compound Operators]
Syntax
Parameters
x: variable. Allowed data types: int, float, double, byte, short, long.
y: variable or constant. Allowed data
types: int, float, double, byte, short, long.
Example Code
x = 2;
x *= 3; // x now contains 6
++
[Compound Operators]
Syntax
Parameters
Example Code
x = 2;
y = ++x; // x now contains 3, y contains 3
y = x++; // x contains 4, but y still contains 3
+=
[Compound Operators]
Syntax
Parameters
x: variable. Allowed data types: int, float, double, byte, short, long.
y: variable or constant. Allowed data
types: int, float, double, byte, short, long.
Example Code
x = 2;
x += 4; // x now contains 6
--
[Compound Operators]
Parameters
Returns
Example Code
x = 2;
y = --x; // x now contains 1, y contains 1
y = x--; // x contains 0, but y still contains 1
-=
[Compound Operators]
Syntax
Parameters
x: variable. Allowed data types: int, float, double, byte, short, long.
y: variable or constant. Allowed data
types: int, float, double, byte, short, long.
Example Code
x = 20;
x -= 2; // x now contains 18
/=
[Compound Operators]
Syntax
Parameters
x: variable. Allowed data types: int, float, double, byte, short, long.
y: non zero variable or constant. Allowed data
types: int, float, double, byte, short, long.
Example Code
x = 2;
x /= 2; // x now contains 1
^=
[Compound Operators]
0 0 1 1 operand1
0 1 0 1 operand2
----------
0 1 1 0 (operand1 ^ operand2) - returned result
Syntax
x ^= y; // equivalent to x = x ^ y;
Parameters
Example Code
1 0 1 0 1 0 1 0 variable
0 0 0 0 0 0 1 1 mask
----------------------
1 0 1 0 1 0 0 1
bits unchanged
bits toggled
Here is the same representation with the variables bits replaced with
the symbol x. ~x represents the complement of 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 ~x ~x
bits unchanged
bits set
So if:
myByte = 0b10101010;
myByte ^= 0b00000011 == 0b10101001;
|=
[Compound Operators]
0 0 1 1 operand1
0 1 0 1 operand2
----------
0 1 1 1 (operand1 | operand2) - returned result
Syntax
x |= y; // equivalent to x = x | y;
Parameters
Example Code
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
bits 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
bits unchanged
bits set
So if:
myByte = 0b10101010;
myByte |= 0b00000011 == 0b10101011;