Arduino Library
Arduino Library
Libraries
1.Basics
AnalogReadSerial: Read a
potentiometer, print it's state
out to the Arduino Serial
Monitor.
ReadAnalogVoltage : Reads an
analog input and prints the
voltage to the serial monitor
2.Digital
Esplora Library
EsploraLightCalibrator : Read
the values from the
accelerometer
EsploraTemperatureSensor :
Read the temperature sensor
and get the temperature in in
Farhenheit or Celsius.
3.Analog
AnalogInOutSerial: read an
analog input pin, map the result,
and then use that data to dim or
brighten an LED.
Ethernet Library
WebClientRepeating: Make
repeated HTTP requests.
PachubeClient: connect to
pachube.com, a free
datalogging site.
4.Communication
ReadASCIIString: parse a
comma-separated string of ints
to fade an LED
ASCII Table: demonstrates
Arduino's advanced serial output
functions.
PachubeClientString: send
strings to pachube.com.
BarometricPressureWebServer:
outputs the values from a
barometric pressure sensor as a
web page.
UDPSendReceiveString: Send
and receive text strings via UDP.
DhcpAddressPrinter: Get an IP
address via DHCP and print it
out
Firmata Libraries
GSM Library
GSM Examples
use of SerialEvent().
5.Control Structures
GSM Tools
port.
6.Sensors
Memsic2125 : two-axis
acceleromoter.
7.Display
8.Strings
StringAdditionOperator: add
strings together in a variety of
ways.
StringAppendOperator: append
data to strings.
Robot Library
StringComparisonOperators:
compare strings alphabetically.
StringConstructors: how to
StringStartsWithEndsWith: check
which characters/substrings a
given string starts or ends with.
SPI Library
9.USB (Leonardo, Micro, and Due
specific examples)
KeyboardAndMouseControl:
Demonstrates the Mouse and
Keyboard commands in one
program.
BarometricPressureSensor: read
air pressure and temperature
from a sensor using the SPI
protocol.
Servo Library
Keyboard
Mouse
ButtonMouseControl: Control
cursor movement with 5
pushbuttons.
Stepper Library
TFT Library
Esplora
JoystickMouseControl: Controls a
computer's cursor movement
with a Joystick when a button is
pressed.
screen
Arduino
Wire Library
SFRRanger_reader: read a
Devantech SRFxx ultra-sonic
range finder using I2C
communication.
digital_potentiometer: control a
AD5171 digital pot using the
Wire Library.
ConnectNoEncryption :
Demonstrates how to connect to
an open network
ConnectWithWEP :
Demonstrates how to connect to
a network that is encrypted with
WEP
ConnectWithWPA :
Demonstrates how to connect to
a network that is encrypted with
WPA2 Personal
WiFiPachubeClient : connect to
pachube.com, a free
datalogging site
WiFiPachubeClientString: send
strings to pachube.com
WiFiTwitterClient : A Twitter
client with Strings
WiFiWebClient : Connect to a
remote webserver
WiFiWebClientRepeating:
Repeatedly make HTTP calls to a
server
WiFiWebServer : Serve a
webpage from the WiFi shield
Programms - Arduino
Blink
This example shows the simplest thing you can do with an Arduino to see physical output: it
blinks an LED.
Hardware Required
Arduino Board
LED
Circuit
To build the circuit, attach a 220-ohm resistor to pin 13. Then attach the long leg of an LED (the
positive leg, called the anode) to the resistor. Attach the short leg (the negative leg, called the
cathode) to ground. Then plug your Arduino board into your computer, start the Arduino
program, and enter the code below.
Most Arduino boards already have an LED attached to pin 13 on the board itself. If you run this
example with no hardware attached, you should see that LED blink.
Schematic
Code
In the program below, the first thing you do is to initialize pin 13 as an output pin with the line
pinMode(13, OUTPUT);
In the main loop, you turn the LED on with the line:
digitalWrite(13, HIGH);
This supplies 5 volts to pin 13. That creates a voltage difference across the pins of the LED, and
lights it up. Then you turn it off with the line:
digitalWrite(13, LOW);
That takes pin 13 back to 0 volts, and turns the LED off. In between the on and the off, you want
enough time for a person to see the change, so the delay() commands tell the Arduino to do
nothing for 1000 milliseconds, or one second. When you use the delay() command, nothing
else happens for that amount of time. Once you've understood the basic examples, check out the
BlinkWithoutDelay example to learn how to create a delay while doing other things.
Once you've understood this example, check out the DigitalReadSerial example to learn how
read a switch connected to the Arduino.
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.
This example code is in the public domain.
*/
// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;
// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output.
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
delay(1000);
// wait for a second
digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
delay(1000);
setup()
The setup() function is called when a sketch starts. Use it to initialize variables, pin modes, start
using libraries, etc. The setup function will only run once, after each power up or reset of the
Arduino board.
Example
int buttonPin = 3;
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
void loop()
{
// ...
}
loop()
After creating a setup() function, which initializes and sets the initial values, the loop() function
does precisely what its name suggests, and loops consecutively, allowing your program to
change and respond. Use it to actively control the Arduino board.
Example
const int buttonPin = 3;
// setup initializes serial and the button pin
void setup()
{
Serial.begin(9600);
pinMode(buttonPin, INPUT);
}
// loop checks the button pin each time,
// and will send serial if it is pressed
void loop()
{
if (digitalRead(buttonPin) == HIGH)
Serial.write('H');
else
Serial.write('L');
delay(1000);
pinMode()
Description
Configures the specified pin to behave either as an input or an output. See the description of
digital pins for details on the functionality of the pins.
As of Arduino 1.0.1, it is possible to enable the internal pullup resistors with the mode
INPUT_PULLUP. Additionally, the INPUT mode explicitly disables the internal pullups.
Syntax
pinMode(pin, mode)
Parameters
pin: the number of the pin whose mode you wish to set
mode: INPUT, OUTPUT, or INPUT_PULLUP. (see the digital pins page for a more complete
description of the functionality.)
Returns
None
Example
void setup()
{
pinMode(ledPin, 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
}
digitalWrite()
Description
digitalWrite(pin, value)
Parameters
none
Example
int ledPin = 13;
void setup()
{
pinMode(ledPin, OUTPUT);
}
void loop()
{
digitalWrite(ledPin, HIGH);
delay(1000);
digitalWrite(ledPin, LOW);
delay(1000);
//
//
//
//
Sets pin 13 to HIGH, makes a one-second-long delay, and sets the pin back to LOW.
Note
The analog input pins can be used as digital pins, referred to as A0, A1, etc.
delay()
Description
Pauses the program for the amount of time (in miliseconds) specified as parameter. (There are
1000 milliseconds in a second.)
Syntax
delay(ms)
Parameters
nothing
Example
int ledPin = 13;
void setup()
{
pinMode(ledPin, 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
}
Caveat
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 millis() function and the sketch sited below. 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.
Certain things do go on while the delay() function is controlling the Atmega chip however,
because the delay function does not disable interrupts. Serial communication that appears at the
RX pin is recorded, PWM (analogWrite) values and pin states are maintained, and interrupts will
work as they should.
Hardware Required
Arduino Board
breadboard
hook-up wire
Circuit
Connect three wires to the Arduino board. The first two, red and black, connect to the two long
vertical rows on the side of the breadboard to provide access to the 5 volt supply and ground. The
third wire goes from digital pin 2 to one leg of the pushbutton. That same leg of the button
connects through a pull-down resistor (here 10 KOhms) to ground. The other leg of the button
connects to the 5 volt supply.
Pushbuttons or switches connect two points in a circuit when you press them. When the
pushbutton is open (unpressed) there is no connection between the two legs of the pushbutton, so
the pin is connected to ground (through the pull-down resistor) and reads as LOW, or 0. When
the button is closed (pressed), it makes a connection between its two legs, connecting the pin to 5
volts, so that the pin reads as HIGH, or 1.
If you disconnect the digital i/o pin from everything, the LED may blink erratically. This is
because the input is "floating" - that is, it doesn't have a solid connection to voltage or ground,
and it will randomly return either HIGH or LOW. That's why you need a pull-down resistor in
the circuit.
Schematic
Code
In the program below, the very first thing that you do will in the setup function is to begin serial
communications, at 9600 bits of data per second, between your Arduino and your computer with
the line:
Serial.begin(9600);
Next, initialize digital pin 2, the pin that will read the output from your button, as an input:
pinMode(2,INPUT);
Now that your setup has been completed, move into the main loop of your code. When your
button is pressed, 5 volts will freely flow through your circuit, and when it is not pressed, the
input pin will be connected to ground through the 10-kilohm resistor. This is a digital input,
meaning that the switch can only be in either an on state (seen by your Arduino as a "1", or
HIGH) or an off state (seen by your Arduino as a "0", or LOW), with nothing in between.
The first thing you need to do in the main loop of your program is to establish a variable to hold
the information coming in from your switch. Since the information coming in from the switch
will be either a "1" or a "0", you can use an int datatype. Call this variable sensorValue, and
set it to equal whatever is being read on digital pin 2. You can accomplish all this with just one
line of code:
int sensorValue = digitalRead(2);
Once the Arduino has read the input, make it print this information back to the computer as a
decimal value. You can do this with the command Serial.println() in our last line of code:
Serial.println(sensorValue);
Now, when you open your Serial Monitor in the Arduino environment, you will see a stream of
"0"s if your switch is open, or "1"s if your switch is closed.
/*
DigitalReadSerial
Reads a digital input on pin 2, prints the result to the serial monitor
This example code is in the public domain.
*/
// digital pin 2 has a pushbutton attached to it. Give it a name:
int pushButton = 2;
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
// make the pushbutton's pin an input:
pinMode(pushButton, INPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input pin:
int buttonState = digitalRead(pushButton);
// print out the state of the button:
Serial.println(buttonState);
delay(1);
// delay in between reads for stability
}
Hardware Required
Arduino Board
10-kilohm Potentiometer
Circuit
Connect the three wires from the potentiometer to your Arduino board. The first goes to ground
from one of the outer pins of the potentiometer. The second goes from 5 volts to the other outer
pin of the potentiometer. The third goes from analog input 0 to the middle pin of the
potentiometer.
click the image to enlarge
By turning the shaft of the potentiometer, you change the amount of resistance on either side of
the wiper which is connected to the center pin of the potentiometer. This changes the voltage at
the center pin. When the resistance between the center and the side connected to 5 volts is close
to zero (and the resistance on the other side is close to 10 kilohms), the voltage at the center pin
nears 5 volts. When the resistances are reversed, the voltage at the center pin nears 0 volts, or
ground. This voltage is the analog voltage that you're reading as an input.
The Arduino has a circuit inside called an analog-to-digital converter that reads this changing
voltage and converts it to a number between 0 and 1023. When the shaft is turned all the way in
one direction, there are 0 volts going to the pin, and the input value is 0. When the shaft is turned
all the way in the opposite direction, there are 5 volts going to the pin and the input value is
1023. In between, analogRead() returns a number between 0 and 1023 that is proportional to the
amount of voltage being applied to the pin.
Schematic
Code
In the program below, the only thing that you do will in the setup function is to begin serial
communications, at 9600 bits of data per second, between your Arduino and your computer with
the command:
Serial.begin(9600);
Next, in the main loop of your code, you need to establish a variable to store the resistance value
(which will be between 0 and 1023, perfect for an int datatype) coming in from your
potentiometer:
int sensorValue = analogRead(A0);
Finally, you need to print this information to your serial window as a decimal (DEC) value. You
can do this with the command Serial.println() in your last line of code:
Serial.println(sensorValue, DEC)
Now, when you open your Serial Monitor in the Arduino development environment (by clicking
the button directly to the right of the "Upload" button in the header of the program), you should
see a steady stream of numbers ranging from 0-1023, correlating to the position of the pot. As
you turn your potentiometer, these numbers will respond almost instantly.
/*
AnalogReadSerial
Reads an analog input on pin 0, prints the result to the serial monitor.
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
This example code is in the public domain.
*/
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// print out the value you read:
Serial.println(sensorValue);
delay(1);
// delay in between reads for stability
}
int
Description
store negative numbers with a technique called 2's complement math. The highest bit,
sometimes referred to as the "sign" bit, flags the number as a negative number. The rest of the
bits are inverted and 1 is added.
The Arduino takes care of dealing with negative numbers for you, so that arithmetic operations
work transparently in the expected manner. There can be an unexpected complication in dealing
with the bitshift right operator (>>) however.
Example
int ledPin = 13;
Syntax
int var = val;
Coding Tip
When variables are made to exceed their maximum capacity they "roll over" back to their
minimum capacity, note that this happens in both directions. Example for a 16-bit int:
int x;
x = -32768;
x = x - 1;
x = 32767;
x = x + 1;
analogRead()
Description
Reads the value from the specified analog pin. The Arduino board contains a 6 channel (8
channels on the Mini and Nano, 16 on the Mega), 10-bit analog to digital converter. This means
that it will map input voltages between 0 and 5 volts into integer values between 0 and 1023.
This yields a resolution between readings of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per
unit. The input range and resolution can be changed using analogReference().
It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate
is about 10,000 times a second.
Syntax
analogRead(pin)
Parameters
pin: the number of the analog input pin to read from (0 to 5 on most boards, 0 to 7 on the Mini
and Nano, 0 to 15 on the Mega)
Returns
int (0 to 1023)
Note
If the analog input pin is not connected to anything, the value returned by analogRead() will
fluctuate based on a number of factors (e.g. the values of the other analog inputs, how close your
hand is to the board, etc.).
Example
int analogPin = 3;
analog pin 3
int val = 0;
void setup()
{
Serial.begin(9600);
}
void loop()
{
val = analogRead(analogPin);
Serial.println(val);
}
//
setup serial
println()
Description
Prints data to the serial port as human-readable ASCII text followed by a carriage return
character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n'). This command takes the
same forms as Serial.print().
Syntax
Serial.println(val)
Serial.println(val, format)
Parameters
size_t (long): println() returns the number of bytes written, though reading that number is
optional
Example:
/*
Analog input
reads an analog input on analog in 0, prints the value out.
created 24 March 2006
by Tom Igoe
*/
int analogValue = 0;
void setup() {
// open the serial port at 9600 bps:
Serial.begin(9600);
}
void loop() {
// read the analog input on pin 0:
analogValue = analogRead(0);
Fading
Demonstrates the use of the analogWrite() function in fading an LED off and on. AnalogWrite
uses pulse width modulation (PWM), turning a digital pin on and off very quickly, to create a
fading effect.
Hardware Required
Arduino board
Breadboard
a LED
Circuit
Connect the anode (the longer, positive leg) of your LED to digital output pin 9 on your Arduino
through a 220-ohm resistor. Connect the cathode (the shorter, negative leg) directly to ground.
Schematic
Code
After declaring pin 9 to be your ledPin, there is nothing to do in the setup() function of your
code.
The analogWrite() function that you will be using in the main loop of your code requires two
arguments: One telling the function which pin to write to, and one indicating what PWM value to
write.
In order to fade your LED off and on, gradually increase your PWM value from 0 (all the way
off) to 255 (all the way on), and then back to 0 once again to complete the cycle. In the sketch
below, the PWM value is set using a variable called brightness. Each time through the loop, it
increases by the value of the variable fadeAmount.
If brightness is at either extreme of its value (either 0 or 255), then fadeAmount is changed to
its negative. In other words, if fadeAmount is 5, then it is set to -5. If it's 55, then it's set to 5. The
next time through the loop, this change causes brightness to change direction as well.
can change the PWM value very fast, so the delay at the end of the sketch
controls the speed of the fade. Try changing the value of the delay and see how it changes the
program.
analogWrite()
/*
Fade
This example shows how to fade an LED on pin 9
using the analogWrite() function.
This example code is in the public domain.
*/
int led = 9;
// the pin that the LED is attached to
int brightness = 0; // how bright the LED is
int fadeAmount = 5; // how many points to fade the LED by
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(led, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
// set the brightness of pin 9:
analogWrite(led, brightness);
// change the brightness for next time through the loop:
brightness = brightness + fadeAmount;
// reverse the direction of the fading at the ends of the fade:
if (brightness == 0 || brightness == 255) {
fadeAmount = -fadeAmount ;
}
// wait for 30 milliseconds to see the dimming effect
delay(30);
}
PWM
The Fading example demonstrates the use of analog output (PWM) to fade an LED. It is
available in the File->Sketchbook->Examples->Analog menu of the Arduino software.
Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means.
Digital control is used to create a square wave, a signal switched between on and off. This on-off
pattern can simulate voltages in between full on (5 Volts) and off (0 Volts) by changing the
portion of the time the signal spends on versus the time that the signal spends off. The duration
of "on time" is called the pulse width. To get varying analog values, you change, or modulate,
that pulse width. If you repeat this on-off pattern fast enough with an LED for example, the result
is as if the signal is a steady voltage between 0 and 5v controlling the brightness of the LED.
In the graphic below, the green lines represent a regular time period. This duration or period is
the inverse of the PWM frequency. In other words, with Arduino's PWM frequency at about
500Hz, the green lines would measure 2 milliseconds each. A call to analogWrite() is on a scale
of 0 - 255, such that analogWrite(255) requests a 100% duty cycle (always on), and
analogWrite(127) is a 50% duty cycle (on half the time) for example.
Once you get this example running, grab your arduino and shake it back and forth. What you are
doing here is essentially mapping time across the space. To our eyes, the movement blurs each
LED blink into a line. As the LED fades in and out, those little lines will grow and shrink in
length. Now you are seeing the pulse width.
for statements
Desciption
The for statement is used to repeat a block of statements enclosed in curly braces. An increment
counter is usually used to increment and terminate the loop. The for statement is useful for any
repetitive operation, and is often used in combination with arrays to operate on collections of
data/pins.
There are three parts to the for loop header:
for (initialization; condition; increment) {
//statement(s);
}
The initialization happens first and exactly once. Each time through the loop, the condition is
tested; if it's true, the statement block, and the increment is executed, then the condition is
tested again. When the condition becomes false, the loop ends.
Example
// Dim an LED using a PWM pin
int PWMpin = 10; // LED in series with 470 ohm resistor on pin 10
void setup()
{
// no setup needed
}
void loop()
{
Coding Tips
The C for loop is much more flexible than for loops found in some other computer languages,
including BASIC. Any or all of the three header elements may be omitted, although the
semicolons are required. Also the statements for initialization, condition, and increment can be
any valid C statements with unrelated variables, and use any C datatypes including floats. These
types of unusual for statements may provide solutions to some rare programming problems.
For example, using a multiplication in the increment line will generate a logarithmic progression:
for(int x = 2; x < 100; x = x * 1.5){
println(x);
}
Generates: 2,3,4,6,9,13,19,28,42,63,94
Another example, fade an LED up and down with one for loop:
void loop()
{
int x = 1;
for (int i = 0; i > -1; i = i + x){
analogWrite(PWMpin, i);
if (i == 255) x = -1;
delay(10);
}
}
while loops
Description
while loops will loop continuously, and infinitely, until the expression inside the parenthesis, ()
becomes false. Something must change the tested variable, or the while loop will never exit. This
could be in your code, such as an incremented variable, or an external condition, such as testing a
sensor.
Syntax
while(expression){
// statement(s)
}
Parameters
Hardware Required
Arduino Board
Circuit
Connect the three wires from the potentiometer to your Arduino board. The first goes to ground
from one of the outer pins of the potentiometer. The second goes from 5 volts to the other outer
pin of the potentiometer. The third goes from analog input 2 to the middle pin of the
potentiometer.
By turning the shaft of the potentiometer, you change the amount of resistance on either side of
the wiper which is connected to the center pin of the potentiometer. This changes the voltage at
the center pin. When the resistance between the center and the side connected to 5 volts is close
to zero (and the resistance on the other side is close to 10 kilohms), the voltage at the center pin
nears 5 volts. When the resistances are reversed, the voltage at the center pin nears 0 volts, or
ground. This voltage is the analog voltage that you're reading as an input.
The Arduino has a circuit inside called an analog-to-digital converter that reads this changing
voltage and converts it to a number between 0 and 1023. When the shaft is turned all the way in
one direction, there are 0 volts going to the pin, and the input value is 0. When the shaft is turned
all the way in the opposite direction, there are 5 volts going to the pin and the input value is
1023. In between, analogRead() returns a number between 0 and 1023 that is proportional to the
amount of voltage being applied to the pin.
Schematic
Code
In the program below, the very first thing that you do will in the setup function is to begin serial
communications, at 9600 bits of data per second, between your Arduino and your computer with
the line:
Serial.begin(9600);
Next, in the main loop of your code, you need to establish a variable to store the resistance value
(which will be between 0 and 1023, perfect for an int datatype) coming in from your
potentiometer:
int sensorValue = analogRead(A0);
To change the values from 0-1023 to a range that corresponds to the voltage the pin is reading,
you'll need to create another variable, a float, and do a little math. To scale the numbers
between 0.0 and 5.0, divide 5.0 by 1023.0 and multiply that by sensorValue :
float voltage= sensorValue * (5.0 / 1024.0);
Finally, you need to print this information to your serial window as. You can do this with the
command Serial.println() in your last line of code:
Serial.println(voltage)
Now, when you open your Serial Monitor in the Arduino development environment (by clicking
the button directly to the right of the "Upload" button in the header of the program), you should
see a steady stream of numbers ranging from 0.0 - 5.0. As you turn the pot, the values will
change, corresponding to the voltage coming into pin A0.
/*
ReadAnalogVoltage
Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
This example code is in the public domain.
*/
// the setup routine runs once when you press reset:
void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
// the loop routine runs over and over again forever:
void loop() {
// read the input on analog pin 0:
int sensorValue = analogRead(A0);
// Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
float voltage = sensorValue * (5.0 / 1023.0);
// print out the value you read:
Serial.println(voltage);
}
float
Description
Datatype for floating-point numbers, a number that has a decimal point. Floating-point numbers
are often used to approximate analog and continuous values because they have greater resolution
than integers. Floating-point numbers can be as large as 3.4028235E+38 and as low as
-3.4028235E+38. They are stored as 32 bits (4 bytes) of information.
Floats have 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
6.0 / 3.0 may not equal 2.0. You should instead check that the absolute value of the difference
between the numbers is less than some small number.
Floating point math is also much slower than integer math in performing calculations, so should
be avoided if, for example, a loop has to run at top speed for a critical timing function.
Programmers often go to some lengths to convert floating point calculations to integer math to
increase speed.
Examples
float myfloat;
float sensorCalbrate = 1.117;
Syntax
float var = val;
Example Code
int x;
int y;
float z;
x = 1;
y = x / 2;
z = (float)x / 2.0;
Serial
Used for communication between the Arduino board and a computer or other devices. All Arduino boards have a
You can use the Arduino environment's built-in serial monitor to communicate with an Arduino board. Click the
The Arduino Mega has three additional serial ports: Serial1 on pins 19 (RX) and 18 (TX), Serial2 on pins 17 (R
communicate with an external TTL serial device, connect the TX pin to your device's RX pin, the RX to your dev
The Arduino Due has three additional 3.3V TTL serial ports: Serial1 on pins 19 (RX) and 18 (TX); Serial2 on p
on the SAM3X chip, SerialUSB'.
The Arduino Leonardo board uses Serial1 to communicate via TTL (5V) serial on pins 0 (RX) and 1 (TX). Seria
Arduino
int
Description
store negative numbers with a technique called 2's complement math. The highest bit,
sometimes referred to as the "sign" bit, flags the number as a negative number. The rest of the
bits are inverted and 1 is added.
The Arduino takes care of dealing with negative numbers for you, so that arithmetic operations
work transparently in the expected manner. There can be an unexpected complication in dealing
with the bitshift right operator (>>) however.
Example
int ledPin = 13;
Syntax
int var = val;
Coding Tip
When variables are made to exceed their maximum capacity they "roll over" back to their
minimum capacity, note that this happens in both directions. Example for a 16-bit int:
int x;
x = -32768;
x = x - 1;
x = 32767;
x = x + 1;
Variables
A variable is a way of naming and storing a value for later use by the program, such as data from
a sensor or an intermediate value used in a calculation.
Declaring Variables
Before they are used, all variables have to be declared. Declaring a variable means defining its
type, and optionally, setting an initial value (initializing the variable). Variables do not have to be
initialized (assigned a value) when they are declared, but it is often useful.
int inputVariable1;
int inputVariable2 = 0;
Programmers should consider the size of the numbers they wish to store in choosing variable
types. Variables will roll over when the value stored exceeds the space assigned to store it. See
below for an example.
Variable Scope
Another important choice that programmers face is where to declare variables. The specific place
that variables are declared influences how various functions in a program will see the variable.
This is called variable scope.
Initializing Variables
Variables may be initialized (assigned a starting value) when they are declared or not. It is
always good programming practice however to double check that a variable has valid data in it,
before it is accessed for some other purpose.
Example:
int calibrationVal = 17;
Variable Rollover
When variables are made to exceed their maximum capacity they "roll over" back to their
minimum capacity, note that this happens in both directions.
int
x =
x =
x =
x =
x
-32,768;
x - 1;
32,767;
x + 1;
Using Variables
Once variables have been declared, they are used by setting the variable equal to the value one
wishes to store with the assignment operator (single equal sign). The assignment operator tells
the program to put whatever is on the right side of the equal sign into the variable on the left
side.
inputVariable1 = 7;
// sets the variable named inputVariable1 to 7
inputVariable2 = analogRead(2); // sets the variable named inputVariable2 to
the
// (digitized) input voltage read from analog
pin #2
Examples
int lightSensVal;
char currentLetter;
unsigned long speedOfLight = 186000UL;
char errorMessage = {"choose another option"}; // see string
Once a variable has been set (assigned a value), you can test its value to see if it meets certain
conditions, or you can use its value directly. For instance, the following code tests whether the
inputVariable2 is less than 100, then sets a delay based on inputVariable2 which is a minimum of
100:
if (inputVariable2 < 100)
{
inputVariable2 = 100;
}
delay(inputVariable2);
This example shows all three useful operations with variables. It tests the variable ( if
(inputVariable2 < 100) ), it sets the variable if it passes the test ( inputVariable2 = 100 ),
and it uses the value of the variable as an input parameter to the delay() function
( delay(inputVariable2) )
Style Note: You should give your variables descriptive names, so as to make your code more
readable. Variable names like tiltSensor or pushButton help you (and anyone else reading your
code) understand what the variable represents. Variable names like var or value, on the other
hand, do little to make your code readable.
You can name a variable any word that is not already one of the keywords in Arduino. Avoid
beginning variable names with numeral characters.
Integer Constants
Integer constants are numbers used directly in a sketch, like 123. By default, these numbers are
treated as int's but you can change this with the U and L modifiers (see below).
Normally, integer constants are treated as base 10 (decimal) integers, but special notation
(formatters) may be used to enter numbers in other bases.
Base
Example
10 (decimal)
2 (binary)
to 255)
123
Formatter
Comment
B1111011
none
leading 'B'
8 (octal)
0173
leading "0"
16 (hexadecimal)
0x7B
leading "0x"
Decimal is base 10. This is the common-sense math with which you are acquainted. Constants
without other prefixes are assumed to be in decimal format.
Example:
101
B101
// same as 5 decimal
The binary formatter only works on bytes (8 bits) between 0 (B0) and 255 (B11111111). If it is
convenient to input an int (16 bits) in binary form you can do it a two-step procedure such as:
myInt = (B11001100 * 256) + B10101010;
Octal is base eight. Only characters 0 through 7 are valid. Octal values are indicated by the
prefix "0"
Example:
0101
Warning
// same as 65 decimal
Hexadecimal (or hex) is base sixteen. Valid characters are 0 through 9 and letters A through F; A
has the value 10, B is 11, up to F, which is 15. Hex values are indicated by the prefix "0x". Note
that A-F may be syted in upper or lower case (a-f).
Example:
0x101
U & L formatters
By default, an integer constant is treated as an int with the attendant limitations in values. To
specify an integer constant with another data type, follow it with:
a 'u' or 'U' to force the constant into an unsigned data format. Example: 33u
a 'l' or 'L' to force the constant into a long data format. Example: 100000L
a 'ul' or 'UL' to force the constant into an unsigned long constant. Example:
32767ul
unsigned long
Description
Unsigned long variables are extended size variables for number storage, and store 32 bits (4
bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range
from 0 to 4,294,967,295 (2^32 - 1).
Example
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);
}
Syntax
unsigned long var = val;
long
Description
Long variables are extended size variables for number storage, and store 32 bits (4 bytes), from
-2,147,483,648 to 2,147,483,647.
Example
long speedOfLight = 186000L;
the 'L'
Syntax
long var = val;
unsigned int
Description
On the Uno and other ATMEGA based boards, unsigned ints (unsigned integers) are the same as
ints in that they store a 2 byte value. Instead of storing negative numbers however they only store
positive values, yielding a useful range of 0 to 65,535 (2^16) - 1).
The Due stores a 4 byte (32-bit) value, ranging from 0 to 4,294,967,295 (2^32 - 1).
The difference between unsigned ints and (signed) ints, lies in the way the highest bit, sometimes
refered to as the "sign" bit, is interpreted. In the Arduino int type (which is signed), if the high bit
is a "1", the number is interpreted as a negative number, and the other 15 bits are interpreted with
2's complement math.
Example
unsigned int ledPin = 13;
Syntax
unsigned int var = val;
Coding Tip
When variables are made to exceed their maximum capacity they "roll over" back to their
minimum capacitiy, note that this happens in both directions
unsigned int x
x = 0;
x = x - 1;
x = x + 1;
byte
Description
println()
Description
Prints data to the serial port as human-readable ASCII text followed by a carriage return
character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n'). This command takes the
same forms as Serial.print().
Syntax
Serial.println(val)
Serial.println(val, format)
Parameters
size_t (long): println() returns the number of bytes written, though reading that number is
optional
Example:
/*
Analog input
reads an analog input on analog in 0, prints the value out.
created 24 March 2006
by Tom Igoe
*/
int analogValue = 0;
void setup() {
// open the serial port at 9600 bps:
Serial.begin(9600);
}
void loop() {
// read the analog input on pin 0:
analogValue = analogRead(0);
// print it out in many formats:
Serial.println(analogValue);
// print as an ASCII-encoded decimal
Serial.println(analogValue, DEC); // print as an ASCII-encoded decimal
Serial.println(analogValue, HEX); // print as an ASCII-encoded hexadecimal
Serial.println(analogValue, OCT); // print as an ASCII-encoded octal
Serial.println(analogValue, BIN); // print as an ASCII-encoded binary
// delay 10 milliseconds before the next reading:
delay(10);
}
if (Serial)
Description
All boards:
if (Serial)
Arduino Leonardo specific:
if (Serial1)
Arduino Mega specific:
if (Serial1)
if (Serial2)
if (Serial3)
Parameters
none
Returns
boolean : 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.
Example:
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
}
void loop() {
//proceed normally
}
available()
Description
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). available() inherits
from the Stream utility class.
Syntax
Serial.available()
Arduino Mega only:
Serial1.available()
Serial2.available()
Serial3.available()
Parameters
none
Returns
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}
[Get Code]
begin()
Description
Sets the data rate in bits per second (baud) for serial data transmission. For communicating with
the computer, use one of these rates: 300, 600, 1200, 2400, 4800, 9600, 14400, 19200, 28800,
38400, 57600, or 115200. You can, however, specify other rates - for example, to communicate
over pins 0 and 1 with a component that requires a particular baud rate.
An optional second argument configures the data, parity, and stop bits. The default is 8 data bits,
no parity, one stop bit.
Syntax
Serial.begin(speed)
Serial.begin(speed, config)
Arduino Mega only:
Serial1.begin(speed)
Serial2.begin(speed)
Serial3.begin(speed)
Serial1.begin(speed, config)
Serial2.begin(speed, config)
Serial3.begin(speed, config)
Parameters
SERIAL_5N1
SERIAL_6N1
SERIAL_7N1
SERIAL_5N2
SERIAL_6N2
SERIAL_7N2
SERIAL_8N2
SERIAL_5E1
SERIAL_6E1
SERIAL_7E1
SERIAL_8E1
SERIAL_5E2
SERIAL_6E2
SERIAL_7E2
SERIAL_8E2
SERIAL_5O1
SERIAL_6O1
SERIAL_7O1
SERIAL_8O1
SERIAL_5O2
SERIAL_6O2
SERIAL_7O2
SERIAL_8O2
Returns
nothing
Example:
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
void loop() {}
[Get Code]
end()
Description
Disables serial communication, allowing the RX and TX pins to be used for general input and
output. To re-enable serial communication, call Serial.begin().
Syntax
Serial.end()
Arduino Mega only:
Serial1.end()
Serial2.end()
Serial3.end()
Serial.find()
Description
Serial.find() reads data from the serial buffer until the target string of given length is found. The
function returns true if target string is found, false if it times out.
Serial.flush() inherits from the Stream utility class.
Syntax
Serial.find(target)
Parameters
boolean
Serial.findUntil()
Description
Serial.findUntil() reads data from the serial buffer until a target string of given length or
terminator string is found.
The function returns true if the target string is found, false if it times out.
Serial.findUntil() inherits from the Stream utility class.
Syntax
Serial.findUntil(target, terminal)
Parameters
boolean
flush()
Description
Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead
removed any buffered incoming serial data.)
flush() inherits from the Stream utility class.
Syntax
Serial.flush()
Arduino Mega only:
Serial1.flush()
Serial2.flush()
Serial3.flush()
Parameters
none
Returns
nothing
Serial.parseFloat()
Description
Serial.parseFloat() returns the first valid floating point number from the Serial buffer. Characters
that are not digits (or the minus sign) are skipped. parseFloat() is terminated by the first character
that is not a floating point number.
Serial.parseFloat() inherits from the Stream utility class.
Syntax
Serial.parseFloat()
Parameters
none
Returns
float
parseInt()
Description
Looks for the next valid integer in the incoming serial stream. parseInt() inherits from the Stream
utility class.
If no valid integer is found within one second (adjustable through Serial.setTimeout() ) a default
value of 0 will be returned.
Syntax
Serial.parseInt()
Arduino Mega only:
Serial1.parseInt()
Serial2.parseInt()
Serial3.parseInt()
Parameters
none
Returns
peek()
Description
Returns the next byte (character) of incoming serial data without removing it from the internal
serial buffer. That is, successive calls to peek() will return the same character, as will the next
call to read(). peek() inherits from the Stream utility class.
Syntax
Serial.peek()
Arduino Mega only:
Serial1.peek()
Serial2.peek()
Serial3.peek()
Parameters
None
Returns
the first byte of incoming serial data available (or -1 if no data is available) - int
print()
Description
Prints data to the serial port as human-readable ASCII text. This command can take many forms.
Numbers are printed using an ASCII character for each digit. Floats are similarly printed as
ASCII digits, defaulting to two decimal places. Bytes are sent as a single character. Characters
and strings are sent as is. For example:
An optional second parameter specifies the base (format) to use; permitted values are BIN
(binary, or base 2), OCT (octal, or base 8), DEC (decimal, or base 10), HEX (hexadecimal, or
base 16). For floating point numbers, this parameter specifies the number of decimal places to
use. For example:
You can pass flash-memory based strings to Serial.print() by wrapping them with F(). For
example :
Serial.print(F(Hello World))
Serial.print(val)
Serial.print(val, format)
Parameters
size_t (long): print() returns the number of bytes written, though reading that number is optional
Example:
/*
Uses a FOR loop for data and prints a number in various formats.
*/
int x = 0; // variable
void setup() {
Serial.begin(9600);
}
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.print("\t");
for(x=0; x< 64; x++){
}
Programming Tips
As of version 1.0, serial transmission is asynchronous; Serial.print() will return before any
characters are transmitted.
println()
Description
Prints data to the serial port as human-readable ASCII text followed by a carriage return
character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n'). This command takes the
same forms as Serial.print().
Syntax
Serial.println(val)
Serial.println(val, format)
Parameters
size_t (long): println() returns the number of bytes written, though reading that number is
optional
Example:
/*
Analog input
reads an analog input on analog in 0, prints the value out.
created 24 March 2006
by Tom Igoe
*/
int analogValue = 0;
void setup() {
// open the serial port at 9600 bps:
Serial.begin(9600);
}
void loop() {
// read the analog input on pin 0:
analogValue = analogRead(0);
read()
Description
Reads incoming serial data. read() inherits from the Stream utility class.
Syntax
Serial.read()
Arduino Mega only:
Serial1.read()
Serial2.read()
Serial3.read()
Parameters
None
Returns
the first byte of incoming serial data available (or -1 if no data is available) - int
Example
int incomingByte = 0; // for incoming serial data
void setup() {
Serial.begin(9600);
}
void loop() {
// send data only when you receive data:
if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(incomingByte, DEC);
}
}
Serial.readBytes()
Description
Serial.readBytes() reads characters from the serial port into a buffer. The function terminates if
the determined length has been read, or it times out (see Serial.setTimeout()).
Serial.readBytes() returns the number of characters placed in the buffer. A 0 means no valid data
was found.
Serial.readBytes() inherits from the Stream utility class.
Syntax
Serial.readBytes(buffer, length)
Parameters
byte
Serial.readBytesUntil()
Description
Serial.readBytesUntil() reads characters from the serial buffer into an array. The function
terminates if the terminator character is detected, the determined length has been read, or it times
out (see Serial.setTimeout()).
Serial.readBytesUntil() returns the number of characters read into the buffer. A 0 means no valid
data was found.
Serial.readBytesUntil() inherits from the Stream utility class.
Syntax
byte
Serial.setTimeout()
Description
Serial.setTimeout() sets the maximum milliseconds to wait for serial data when using
Serial.readBytesUntil() or Serial.readBytes(). It defaults to 1000 milliseconds.
Serial.setTimeout() inherits from the Stream utility class.
Syntax
Serial.setTimeout(time)
Parameters
Parameters
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)
Arduino Mega also supports: Serial1, Serial2, Serial3 (in place of Serial)
Parameters
byte
write() will return the number of bytes written, though reading that number is optional
Example
void setup(){
Serial.begin(9600);
}
void loop(){
2.Digital
Blink Without Delay: blinking an LED without using the delay() function.
Hardware Required
Arduino Board
LED
Circuit
To build the circuit, grab an LED and attach its long, positive leg (called the anode) to pin 13.
Attach the short, negative leg (called the cathode) to ground. Then plug your Arduino board into
your computer, start the Arduino program, and enter the code below.
Schematic:
click the image to enlarge
Code
The code below uses the millis() function, a command that returns the number of milliseconds
since the Arduino board started running its current program, to blink an LED.
/* Blink without Delay
Turns on and off a light emitting diode(LED) connected to a digital
pin, without using the delay() function. This means that other code
can run at the same time without being interrupted by the LED code.
The circuit:
* LED attached from pin 13 to ground.
* Note: on most Arduinos, there is already an LED on the board
that's attached to pin 13, so no hardware is needed for this example.
created 2005
by David A. Mellis
modified 8 Feb 2010
by Paul Stoffregen
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/
// constants won't change. Used here to
// set pin numbers:
const int ledPin = 13; // the number of the LED pin
// Variables will change:
int ledState = LOW;
long previousMillis = 0;
Hardware Required
Arduino Board
Circuit
Only your Arduino Board is needed for this example.
Code
The setup() function is called when a sketch starts. Use it to initialize variables, pin modes,
start using libraries, etc. The setup function will only run once, after each powerup or reset of the
Arduino board.
After creating a setup() function, the loop() function does precisely what its name suggests,
and loops consecutively, allowing your program to change and respond as it runs. Code in the
loop() section of your sketch is used to actively control the Arduino board.
The code below won't actually do anything, but it's structure is useful for copying and pasting to
get you started on any sketch of your own. It also shows you how to make comments in your
code.
Any line that starts with two slashes (//) will not be read by the compiler, so you can write
anything you want after it. Commenting your code like this can be particularly helpful in
explaining, both to yourself and others, how your program functions step by step.
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
millis()
Description
Returns the number of milliseconds since the Arduino board began running the current program.
This number will overflow (go back to zero), after approximately 50 days.
Parameters
None
Returns
Tip:
Note that the parameter for millis is an unsigned long, errors may be generated if a programmer
tries to do math with other datatypes such as ints.
Button
Pushbuttons or switches connect two points in a circuit when you press them. This example turns
on the built-in LED on pin 13 when you press the button.
Hardware
Arduino Board
breadboard
hook-up wire
Circuit
Connect three wires to the Arduino board. The first two, red and black, connect to the two long
vertical rows on the side of the breadboard to provide access to the 5 volt supply and ground. The
third wire goes from digital pin 2 to one leg of the pushbutton. That same leg of the button
connects through a pull-down resistor (here 10 KOhms) to ground. The other leg of the button
connects to the 5 volt supply.
When the pushbutton is open (unpressed) there is no connection between the two legs of the
pushbutton, so the pin is connected to ground (through the pull-down resistor) and we read a
LOW. When the button is closed (pressed), it makes a connection between its two legs,
connecting the pin to 5 volts, so that we read a HIGH.
You can also wire this circuit the opposite way, with a pullup resistor keeping the input HIGH,
and going LOW when the button is pressed. If so, the behavior of the sketch will be reversed,
with the LED normally on and turning off when you press the button.
If you disconnect the digital i/o pin from everything, the LED may blink erratically. This is
because the input is "floating" - that is, it will randomly return either HIGH or LOW. That's why
you need a pull-up or pull-down resistor in the circuit.
Schematic:
click the image to enlarge
Code
/*
Button
Turns on and off a light emitting diode(LED) connected to digital
pin 13, when pressing a pushbutton attached to pin 2.
The circuit:
* LED attached from pin 13 to ground
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
* Note: on most Arduinos there is already an LED on the board
attached to pin 13.
created 2005
by DojoDave <http://www.0j0.org>
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Button
*/
// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
// variables will change:
int buttonState = 0;
// variable for reading the pushbutton status
void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}
void loop(){
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
}
else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
pinMode()
Description
Configures the specified pin to behave either as an input or an output. See the description of
digital pins for details on the functionality of the pins.
As of Arduino 1.0.1, it is possible to enable the internal pullup resistors with the mode
INPUT_PULLUP. Additionally, the INPUT mode explicitly disables the internal pullups.
Syntax
pinMode(pin, mode)
Parameters
pin: the number of the pin whose mode you wish to set
mode: INPUT, OUTPUT, or INPUT_PULLUP. (see the digital pins page for a more complete
description of the functionality.)
Returns
None
Example
void setup()
{
pinMode(ledPin, 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
}
if / else
if/else allows greater control over the flow of code than the basic if statement, by allowing
multiple tests to be grouped together. For example, an analog input could be tested and one
action taken if the input was less than 500, and another action taken if the input was 500 or
greater. The code would look like this:
if (pinFiveInput < 500)
{
// action A
}
else
{
// action B
}
else can proceed another if test, so that multiple, mutually exclusive tests can be run at the same
time.
Each test will proceed to the next one until a true test is encountered. When a true test is found,
its associated block of code is run, and the program then skips to the line following the entire
if/else construction. If no test proves to be true, the default else block is executed, if one is
present, and sets the default behavior.
Note that an else if block may be used with or without a terminating else block and vice versa.
An unlimited number of such else if branches is allowed.
if (pinFiveInput < 500)
{
// do Thing A
}
else if (pinFiveInput >= 1000)
{
// do Thing B
}
else
{
// do Thing C
}
Another way to express branching, mutually exclusive tests, is with the switch case statement.
which is used in conjunction with a comparison operator, tests whether a certain condition
has been reached, such as an input being above a certain number. The format for an if test is:
if (someVariable > 50)
{
// do something here
}
The program tests to see if someVariable is greater than 50. If it is, the program takes a particular
action. Put another way, if the statement in parentheses is true, the statements inside the brackets
are run. If not, the program skips over the code.
The brackets may be omitted after an if statement. If this is done, the next line (defined by the
semicolon) becomes the only conditional statement.
if (x > 120) digitalWrite(LEDpin, HIGH);
if (x > 120)
digitalWrite(LEDpin, HIGH);
if (x > 120){ digitalWrite(LEDpin, HIGH); }
if (x > 120){
digitalWrite(LEDpin1, HIGH);
digitalWrite(LEDpin2, HIGH);
}
The statements being evaluated inside the parentheses require the use of one or more operators:
Comparison Operators:
x
x
x
x
x
x
==
!=
<
>
<=
>=
y
y
y
y
y
y
(x
(x
(x
(x
(x
(x
is
is
is
is
is
is
equal to y)
not equal to
less than y)
greater than
less than or
greater than
y)
y)
equal to y)
or equal to y)
Warning:
Beware of accidentally using the single equal sign (e.g. if (x = 10) ). The single equal sign is
the assignment operator, and sets x to 10 (puts the value 10 into the variable x). Instead use the
double equal sign (e.g. if (x == 10) ), which is the comparison operator, and tests whether x
is equal to 10 or not. The latter statement is only true if x equals 10, but the former statement will
always be true.
This is because C evaluates the statement if (x=10) as follows: 10 is assigned to x (remember
that the single equal sign is the assignment operator), so x now contains 10. Then the 'if'
conditional evaluates 10, which always evaluates to TRUE, since any non-zero number evaluates
to TRUE. Consequently, if (x = 10) will always evaluate to TRUE, which is not the desired
result when using an 'if' statement. Additionally, the variable x will be set to 10, which is also not
a desired action.
if can also be part of a branching control structure using the if...else] construction.