Arduino Programation
Arduino Programation
Functions
Digital I/O
digitalRead()
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
}
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.
digitalWrite()
digitalWrite()
[Digital I/O]
Description
Write a HIGH or a LOW value to a digital pin.
If the pin has been configured as an OUTPUT with pinMode(), its voltage will be
set to the corresponding value: 5V (or 3.3V on 3.3V boards) for HIGH, 0V
(ground) for LOW.
If you do not set the pinMode() to OUTPUT, and connect an LED to a pin, when
calling digitalWrite(HIGH), the LED may appear dim. Without explicitly
setting pinMode(), digitalWrite() will have enabled the internal pull-up
resistor, which acts like a large current-limiting resistor.
Syntax
digitalWrite(pin, value)
Parameters
Returns
Nothing
Example Code
The code makes the digital pin 13 an OUTPUT and toggles it by alternating
between HIGH and LOW at one second pace.
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.
pinMode()
pinMode()
[Digital I/O]
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.
Analog I/O
analogRead()
analogReadResolution()
analogReference()
analogWrite()
analogWriteResolution()
Advanced I/O
noTone()
pulseIn()
pulseInLong()
shiftIn()
shiftOut()
tone()
Time
delay()
delay()
[Time]
Description
Pauses the program for the amount of time (in milliseconds) specified as
parameter. (There are 1000 milliseconds in a second.)
Syntax
delay(ms)
Parameters
ms: the number of milliseconds to pause. Allowed data types: unsigned long.
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
}
While it is easy to create a blinking LED with the delay() function and many
sketches use short delays for such tasks as switch debouncing, the use
of delay() in a sketch has significant drawbacks. No other reading of sensors,
mathematical calculations, or pin manipulation can go on during the delay
function, so in effect, it brings most other activity to a halt. For alternative
approaches to controlling timing see the Blink Without Delay sketch, which
loops, polling the millis() function until enough time has elapsed. More
knowledgeable programmers usually avoid the use of delay() for timing of
events longer than 10’s of milliseconds unless the Arduino sketch is very
simple.
delayMicroseconds()
micros()
millis()
Reference > Language > Functions > Time > Millis
millis()
[Time]
Description
Returns the number of milliseconds passed since the Arduino board began
running the current program. This number will overflow (go back to zero),
after approximately 50 days.
Syntax
time = millis()
Parameters
None
Returns
Example Code
This example code prints on the serial port the number of milliseconds
passed since the Arduino board started running the code itself.
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Time: ");
myTime = millis();
millis() is incremented (for 16 MHz AVR chips and some others) every
1.024 milliseconds, then incrementing by 2 (rather than 1) every 41 or
42 ticks, to pull it back into synch; thus some millis() values are skipped.
For accurate timing over short intervals, consider using micros().
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()
bit()
bitClear()
bitRead()
bitSet()
bitWrite()
highByte()
lowByte()
External Interrupts
attachInterrupt()
detachInterrupt()
digitalPinToInterrupt()
Interrupts
interrupts()
noInterrupts()
Communication
Print
Serial
SPI
Stream
Wire
USB
Keyboard
Mouse
Variables
Constants
HIGH | LOW
[Constants]
Defining Pin Levels: HIGH and LOW
When reading or writing to a digital pin there are only two possible values a
pin can take/be-set-to: HIGH and LOW. These are the same as true and false,
as well as 1 and 0.
HIGH
In this state it can source current, e.g. light an LED that is connected through
a series resistor to ground.
LOW
a voltage less than 1.0V (Approx) is present at the pin (3.3V boards)
When a pin is configured to OUTPUT with pinMode(), and set to LOW with
digitalWrite(), the pin is at 0 volts (both 5V and 3.3V boards). In this state it
can sink current, e.g. light an LED that is connected through a series resistor
to +5 volts (or +3.3 volts).
INPUT
Arduino (ATmega) pins configured as INPUT with pinMode() are said to be in
a high-impedance state. Pins configured as INPUT make extremely small
demands on the circuit that they are sampling, equivalent to a series resistor
of 100 Megohms in front of the pin. This makes them useful for reading a
sensor.
If you have your pin configured as an INPUT, and are reading a switch, when
the switch is in the open state the input pin will be "floating", resulting in
unpredictable results. In order to assure a proper reading when the switch is
open, a pull-up or pull-down resistor must be used. The purpose of this
resistor is to pull the pin to a known state when the switch is open. A 10 K
ohm resistor is usually chosen, as it is a low enough value to reliably prevent
a floating input, and at the same time a high enough value to not draw too
much current when the switch is closed. See the Digital Read Serial tutorial
for more information.
If a pull-down resistor is used, the input pin will be LOW when the switch is
open and HIGH when the switch is closed.
If a pull-up resistor is used, the input pin will be HIGH when the switch is open
and LOW when the switch is closed.
INPUT_PULLUP
See the Input Pullup Serial tutorial for an example of this in use.
Pins configured as inputs with either INPUT or INPUT_PULLUP can be damaged
or destroyed if they are connected to voltages below ground (negative
voltages) or above the positive power rail (5V or 3V).
OUTPUT
Integer Constants
LED_BUILTIN
true | false
Conversion
(unsigned int)
(unsigned long)
byte()
char()
float()
float()
[Conversion]
Description
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()
int()
[Conversion]
Description
int(x)
(int)x (C-style type conversion)
Parameters
Returns
long()
word()
Data Types
array
bool
Reference > Language > Variables > Data types > Bool
bool
[Data Types]
Description
A bool holds one of two values, true or false. (Each bool variable occupies
one byte of memory.)
Syntax
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
byte
char
double
float
int
long
short
size_t
string
String()
unsigned char
unsigned int
unsigned long
void
word
const
scope
static
volatile
Utilities
PROGMEM
sizeof()
Structure
Sketch
loop()
loop()
[Sketch]
Description
After creating a setup() function, which initializes and sets the initial values,
the loop() function does precisely what its name suggests, and loops
consecutively, allowing your program to change and respond. Use it to
actively control the Arduino board.
Example Code
int buttonPin = 3;
delay(1000);
}
setup()
setup()
[Sketch]
Description
Example Code
int buttonPin = 3;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
void loop() {
// ...
}
Control Structure
break
continue
do...while
else
Reference > Language > Structure > Control structure > Else
else
[Control Structure]
Description
The if…else allows greater control over the flow of code than the
basic if statement, by allowing multiple tests to be grouped. An else clause
(if at all exists) will be executed if the condition in the if statement results
in false. The else can proceed another if test, so that multiple, mutually
exclusive tests can be run at the same time.
Each test will proceed to the next one until a true test is encountered. When a
true test is found, its associated block of code is run, and the program then
skips to the line following the entire if/else construction. If no test proves to
be true, the default else block is executed, if one is present, and sets the
default behavior.
Example Code
for
Reference > Language > Structure > Control structure > For
for
[Control Structure]
Description
Syntax
for (initialization; condition; increment) {
// statement(s);
}
Parameters
Example Code
// Brighten an LED using a PWM pin
int PWMpin = 10; // LED in series with 470 ohm resistor from pin 10
to ground
void setup() {
// no setup needed
}
void loop() {
for (int i = 0; i <= 255; i++) {
analogWrite(PWMpin, i);
delay(10);
}
}
The C++ for loop is much more flexible than for loops found in some other
computer languages, including BASIC. Any or all of the three header elements
may be omitted, although the semicolons are required. Also the statements
for initialization, condition, and increment can be any valid C++ statements
with unrelated variables, and use any C++ datatypes including floats. These
types of unusual for statements may provide solutions to some rare
programming problems.
For example, using a multiplication in the increment line will generate a
logarithmic progression:
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
if
if
[Control Structure]
Description
Syntax
if (condition) {
//statement(s)
}
Parameters
Example Code
The brackets may be omitted after an if statement. If this is done, the next
line (defined by the semicolon) becomes the only conditional statement.
if (x > 120)
digitalWrite(LEDpin, HIGH);
if (x > 120) {
digitalWrite(LEDpin1, HIGH);
digitalWrite(LEDpin2, HIGH);
}
// all are correct
The statements being evaluated inside the parentheses require the use of
one or more operators shown below.
Comparison Operators:
x == y (x is equal to y)
x != y (x is not equal to y)
x < y (x is less than y)
x > y (x is greater than y)
x <= y (x is less than or equal to y)
x >= y (x is greater than or equal to y)
Beware of accidentally using the single equal sign (e.g. if (x = 10) ). The
single equal sign is the assignment operator, and sets x to 10 (puts the value
10 into the variable x). Instead use the double equal sign (e.g. if (x == 10) ),
which is the comparison operator, and tests whether x is equal to 10 or not.
The latter statement is only true if x equals 10, but the former statement will
always be true.
return
switch...case
while
Reference > Language > Structure > Control structure > While
while
[Control Structure]
Description
A while loop will loop continuously, and infinitely, until the expression inside
the parenthesis, () becomes false. Something must change the tested
variable, or the while loop will never exit. This could be in your code, such as
an incremented variable, or an external condition, such as testing a sensor.
Syntax
while (condition) {
// statement(s)
}
Parameters
condition: a boolean expression that evaluates to true or false.
Example Code
var = 0;
while (var < 200) {
// do something repetitive 200 times
var++;
}
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
Boolean Operators
! (logical not)
&& (logical and)
|| (logical or)
Bitwise Operators
Compound Operators
%= (compound remainder)
&= (compound bitwise and)
*= (compound multiplication)
++ (increment)
+= (compound addition)
-- (decrement)
-= (compound subtraction)
/= (compound division)
^= (compound bitwise xor)
|= (compound bitwise or)