Referencia del Lenguaje
Los programas hechos con Arduino se dividen en tres partes principales: estructura, valores (variables
y constantes), y funciones. El Lenguaje de programación Arduino se basa en C/C++.
Estructura Variables Funciones
setup() (inicialización) Constantes E/S Digitales
loop() (bucle)
HIGH | LOW pinMode()
Estructuras de control INPUT | OUTPUT digitalWrite()
true | false digitalRead()
if (comparador si- Constantes Numéricas
entonces) E/S Analógicas
if...else (comparador Tipos de Datos
si...sino) analogRead()
for (bucle con contador) boolean (booleano) analogWrite() - PWM
switch case (comparador char (carácter) (modulación por ancho
múltiple) byte de pulso)
while (bucle por int (entero)
comparación booleana) unsigned int (entero sin E/S Avanzadas
do... while (bucle por signo)
comparación booleana) long (entero 32b) tone()
break (salida de bloque unsigned long (entero noTone()
de código) 32b sin signo) shiftOut()
continue (continuación float (en coma flotante) pulseIn()
en bloque de código) double (en coma flotante
return (devuelve valor a de 32b) Tiempo
programa) string (cadena de
caracteres) millis()
Sintaxis array (cadena) micros()
void (vacío) delay()
; (punto y coma) delayMicroseconds()
{} (llaves) Conversión
// (comentarios en una Matemáticas
línea) char()
/* */ (comentarios en byte() min() (mínimo)
múltiples líneas) int() max() (máximo)
long() abs() (valor absoluto)
Operadores Aritméticos float() constrain() (limita)
map() (cambia valor de
= (asignación) rango)
+ (suma) pow() (eleva a un
- (resta) número)
* (multiplicación) sq() (eleva al cuadrado)
/ (división)
% (resto) sqrt() (raíz cuadrada)
Operadores Comparativos Trigonometría
== (igual a) sin() (seno)
!= (distinto de) cos() (coseno)
< (menor que) tan() (tangente)
> (mayor que)
<= (menor o igual que) Números Aleatorios
>= (mayor o igual que)
randomSeed()
Operadores Booleanos random()
&& (y) Comunicación
|| (o)
! (negación) Serial
Stream
Operadores de Composición
USB (Leonardo and Due only)
++ (incrementa)
-- (decrementa) Keyboard
+= (composición suma) Mouse
-= (composición resta)
*= (composición
multiplicación)
/= (composición división)
Referencia de lenguaje (extensión)
El lenguaje Arduino está basado en C/C++ y soporta todas las construcciones de C estándar y algunas
funcionalidades de C++. Vincula la librería AVR Libc y permite el uso de todas sus funciones.
Estructura Variables Funciones
setup() Constantes E/S Digital
loop()
HIGH | LOW pinMode() - modo de pin
Estructuras de control INPUT | OUTPUT (entrada o salida)
true | false digitalWrite() - escritura
if constantes enteros digital
if...else constantes coma flotante digitalRead() - lectura
for digital
switch case Tipos de datos
while E/S Analógica
do... while void - vacío
break boolean - booleano analogReference() -
continue char - carácter (8 bits) referencia analógica
return unsigned char - carácter analogRead() - lectura
goto sin signo analógica
byte - byte analogWrite() - escritura
Más sintaxis int - entero analógica, PWM
unsigned int - entero sin
; (punto y coma) signo E/S Avanzada
{} (llaves) word - palabra
// (comentario de una long - entero grande tone()
sola línea) unsigned long - entero noTone()
/* */ (comentario grande sin signo shiftOut()
multilínea) float - coma flotante pulseIn()
#define (definición de double - doble
precompilador) string - cadena de Tiempo
#include (inclusión de caracteres
código externo) array - matriz millis()
micros()
Operaciones aritméticas Conversión delay()
delayMicroseconds()
= (operador de char()
asignación) byte() Cálculo
+ (suma) int()
- (resta) word() min() - mínimo
* (multiplicación) long() max() - máximo
/ (división) float() abs() - valor absoluto
% (módulo) constrain() - limitación
Ámbito de las variables y map() - mapeo
Operadores de comparación cualificadores pow() - potencia
sqrt() - raíz cuadrada
== (igual a) Ámbito de las variables
!= (distinto de) static - estático Trigonometría
< (menor que) volatile - volátil
> (mayor que) const - constante sin() - seno
<= (menor o igual que) cos() - coseno
>= (mayor o igual que) Utilidades tan() - tangente
Operadores booleanos sizeof() (operador sizeof, Números aleatorios
tamaño de)
&& (y) randomSeed() - semilla
|| (o) aleatoria
! (no, negación) random() - aleatorio
Operadores de acceso a Bits y Bytes
punteros
lowByte() - Byte de
* operador de indirección abajo
& operador de referencia highByte() - Byte de
arriba
Operaciones a nivel de bits bitRead() - lectura de Bit
bitWrite() - escritura de
& (and - 'y' a nivel de Bit
bits) bitSet() - escritura de un
| (or - 'o' a nivel de bits) Bit 1
^ (xor a nivel de bits) bitClear() - escritura de
~ (not a nivel de bits) un Bit 0
<< (desplazamiento de bit()
bits a la izquierda)
>> (desplazamiento de Interrupciones externas
bits a la derecha)
attachInterrupt() -
Operadores compuestos programar interrupción
detachInterrupt() -
++ (incremento) desactivar interrupción
-- (decremento)
+= (suma compuesta) Interrupciones
-= (resta compuesta)
*= (multiplicación interrupts() - habilita las
compuesta) interrupciones
/= (división compuesta) noInterrupts() - desactiva
&= (and - 'y' a nivel de las interrupciones
bits compuesto)
|= (or - 'o' a nivel de bits Comunicación
compuesto)
Serial
Librerías
Las Librerías proveen funcionalidad extra a nuestro sketch, por ejemplo: al trabajar con hardware o al
manipular datos. Para usar una librería dentro de un sketch, puedes seleccionarla desde Sketch >
Import Library (Importar Librería).
Si deseas usar librerías que no vienen junto con Arduino, necesitarás instalarlas. Para hacerlo, descarga
la librería y descomprímela. Debería localizarse en una carpeta propia, y normalmente, contener dos
archivos, uno con sufijo ".h" y otro con sufijo ".cpp". Abre tu carpeta sketchbook de Arduino, si ya
existe una carpeta llamada "libraries", coloca la carpeta de la librería ahí dentro. Reiniciar el IDE de
Arduino para encontrar la nueva librería en el menú Sketch > Import Library.
Para más detalles, ver página Entorno de Arduino: Librerías.
Librerías Estándar
EEPROM - Para leer y escribir en memorias "permanentes".
Ethernet - Para conectar a internet usando el Ethernet Shield?.
Firmata - Para comunicarse con aplicaciones en la computadora usando un protocolo estándar
Serial.
LiquidCrystal - Para controlar Displays de cristal líquido (LCD)
Servo - Para controlar servomotores
SoftwareSerial - Para la comunicación serial de cualquier pin digital.
Stepper - Para controlar motores paso a paso (Stepper motors)
Wire - Interfaz de dos cables, ó Two Wire Interface (TWI/I2C), para enviar y recibir datos a
través de una red de dispositivos y sensores.
Estas librerías son compatibles con versiones de Wiring. Los siguientes enlaces apuntan a la (excelente)
documentación de Wiring:
Matrix - Librería para manipular displays de matrices de LED básicas.
Sprite - Librería básica para manipulacion de sprites para usar en animaciones con matrices de
LEDs.
Librerías Contribuídas
Para instalar una librería contribuída, descomprimirla en la subcarpeta libraries ubicada en el
sketchbook. Para más información, ver Entorno de Arduino.
Comunicación (networking y protocolos):
Messenger - Para procesar mensajes de texto desde la computadora.
NewSoftSerial - Versión mejorada de la librería SoftwareSerial.
OneWire - Controla dispositivos (de Dallas Semiconductor) que usan el protocolo One Wire.
PS2Keyboard - Lee caracteres de un teclado PS2.
Simple Message System - Envía mensajes entre Arduino y la computadora.
SSerial2Mobile - Envía mensajes de texto o emails usando un teléfono móvil (via comandos AT
a través de software serial)
Webduino - Librería de web server extendible (para usar con Arduino Ethernet Shield)
X10 - Para enviar señales X10 a trav{es de lineas de corriente AC.
XBee - Para comunicaciones entre XBees en modo API.
SerialControl - Para controlar remotamente otras Arduino a través de una conexión serial.
Sensores:
Capacitive Sensing - Convertir dos o más pins en sensores capacitivos.
Debounce - Para lectura de inputs digitales con ruido (por ejemplo, botones).
Displays y LEDs:
Improved LCD library Arregla bugs de inicialización de LCD de la librería LCD oficial de
Arduino.
GLCD - Grafica rutinas para LCDs basados en el chipset KS0108 ó equivalentes.
LedControl - Para controlar matrices de LEDs o displays de siete segmentos con MAX7221 ó
MAX7219.
LedControl - Alternativa a la librería Matrix para controlar múltiples LEDs con chips Maxim.
LedDisplay - Control para marquesina de LED HCMS-29xx.
Generación de Frecuencias y Audio:
Tone - Genera frecuencias de audio de onda cuadrada en el background de cualquier pin de un
microcontrolador.
Motores y PWM:
TLC5940 - Controlador de PWM de 16 canales y 12 bits.
Medición de Tiempo:
DateTime - Librería para llevar registro de fecha y hora actual en el software.
Metro - Útil para cronometrar acciones en intervalos regulares.
MsTimer2 - Utiliza timer 2 interrupt para disparar una acción cada N milisegundos.
Utilidades:
TextString, también conocido como String - Maneja strings.
PString - Liviana clase para imprimir en búfer.
Streaming - Método para simplificar declaraciones de impresión.
Guía para escribir tus propias librerías.
Libraries
Examples
Note: these examples are written for Arduino 1.0 Examples from the libraries that are included in the
and later. Arduino software.
Certain functions may not work in earlier versions.
Bridge Library (for the Arduino Yún)
For best results, download the latest version. Core
Functions Bridge: Access the pins of the board with a
web browser.
Simple programs that demonstrate basic Arduino Console ASCII Table: Demonstrates
commands. These are included with the Arduino printing various formats to the Console.
environment; to open them, click the Open button Console Pixel: Control an LED through the
on the toolbar and look in the examples folder. Console.
Console Read: Parse information from the
1.Basics Console and repeat it back.
Datalogger: Store sensor information on a
BareMinimum: The bare minimum of code SD card.
needed to start an Arduino sketch. File Write Script: Demonstrates how to
Blink: Turn an LED on and off. write and execute a shell script with
DigitalReadSerial: Read a switch, print the Process.
state out to the Arduino Serial Monitor. HTTP Client: Create a simple client that
AnalogReadSerial: Read a potentiometer, downloads a webpage and prints it to the
print its state out to the Arduino Serial serial monitor.
Monitor. Process: Demonstrates how to use Process
Fade: Demonstrates the use of analog to run Linux commands.
output to fade an LED. Shell Commands: Use Process to run shell
ReadAnalogVoltage : Reads an analog commands.
input and prints the voltage to the serial Temperature Web Panel: Post sensor data
monitor on a webpage when requested by a
browser.
2.Digital TimeCheck: Get the time from a network
time server and print it to the serial
Blink Without Delay: blinking an LED monitor.
without using the delay() function. WiFiStatus: Runs a pre-configured script
Button: use a pushbutton to control an that reports back the strength of the current
LED. WiFi network.
Debounce: read a pushbutton, filtering Xively Client : Send data from multiple
noise. sensors to Xively with strings.
Button State Change: counting the number Yun Serial Terminal: Access the Linux
of button pushes. Terminal through the serial monitor.
Input Pullup Serial: Demonstrates the use MailboxReadMessage: Send text messages
of INPUT_PULLUP with pinMode(). to the Arduino processor using REST API
Tone: play a melody with a Piezo speaker. through a browser.
Pitch follower: play a pitch on a piezo
speaker depending on an analog input. Temboo examples The Temboo website has a
Simple Keyboard: a three-key musical section dedicated to the reference of the Temboo
keyboard using force sensors and a piezo library and examples contained inside the Arduino
speaker.
Tone4: play tones on multiple speakers IDE. See this page for more information.
sequentially using the tone() command.
Spacebrew examples There are a number of
3.Analog examples for Spacebrew on the Yún included in
the software. For more on Spacebrew, see the
AnalogInOutSerial: Read an analog input project documentation pages.
pin, map the result, and then use that data to
dim or brighten an LED. Linux tips&tricks
Analog Input: Use a potentiometer to
control the blinking of an LED. Pacakage Manager : How to install
AnalogWriteMega: Fade 12 LEDs on and additional software on the Yún.
off, one by one, using an Arduino Mega Extending Yún disk space?: How to expand
board. the Yún disk space using an SD card.
Calibration: Define a maximum and
minimum for expected analog sensor EEPROM Library
values.
Fading: Use an analog output (PWM pin) to EEPROM Clear: Clear the bytes in the
fade an LED. EEPROM.
Smoothing: Smooth multiple readings of an EEPROM Read: Read the EEPROM and
analog input. send its values to the computer.
EEPROM Write: Stores values from an
4.Communication analog input to the EEPROM.
These examples include code that allows the Esplora Library
Arduino to talk to Processing sketches running on
the computer. For more information or to Esplora Beginner examples
download Processing, see processing.org. There
are also Max/MSP patches that can communicate EsploraBlink : Blink the Esplora's RGB
with each Arduino sketch as well. For more on LED.
Max/MSP see Cycling 74. For Pd patches that can EsploraAccelerometer : Read the values
communicate with these sketches, see Scott from the accelerometer.
Fitzgerald's examples. EsploraJoystickMouse : Use the Esplora's
joystick to control the cursor on your
ReadASCIIString: Parse a comma- computer.
separated string of ints to fade an LED. EsploraLedShow : Use the Joystick and
ASCII Table: Demonstrates Arduino's slider to create a light show with the LED.
advanced serial output functions. EsploraLedShow2 : Use the Esplora's
Dimmer: Move the mouse to change the microphone, linear potentiometer, and light
brightness of an LED. sensor to change the color of the onboard
Graph: Send data to the computer and LED.
graph it in Processing. EsploraLightCalibrator : Read the values
Physical Pixel: Turn a LED on and off by from the accelerometer.
sending data to your Arduino from EsploraMusic : Make some music with the
Processing or Max/MSP. Esplora.
Virtual Color Mixer: Send multiple EsploraSoundSensor : Read the values from
variables from Arduino to your computer the Esplora's microphone.
and read them in Processing or Max/MSP. EsploraTemperatureSensor : Read the
Serial Call Response: Send multiple temperature sensor and get the temperature
variables using a call-and-response in in Farhenheit or Celsius.
(handshaking) method.
Serial Call Response ASCII: Send multiple Esplora Expert examples
variables using a call-and-response
(handshaking) method, and ASCII-encode EsploraKart : Use the Esplora as a
the values before sending. controller to play a kart racing game.
SerialEvent: Demonstrates the use of EsploraTable : Print the Esplora sensor
SerialEvent(). information to a table format.
Serial input (Switch (case) Statement): EsploraRemote : Connect the Esplora to
How to take different actions based on Processing and control the outputs.
characters received by the serial port. EsploraPong : Play Pong with the Esplora
MIDI: Send MIDI note messages serially. using Processing.
MultiSerialMega: Use two of the serial
ports available on the Arduino Mega. Ethernet Library
5.Control Structures ChatServer: Set up a simple chat server.
WebClient: Make a HTTP request.
If Statement (Conditional): How to use an WebClientRepeating: Make repeated HTTP
if statement to change output conditions requests.
based on changing input conditions. WebServer: Host a simple HTML page that
For Loop: Controlling multiple LEDs with displays analog sensor values.
a for loop and. XivelyClient: Connect to xively.com, a free
Array: A variation on the For Loop datalogging site.
example that demonstrates how to use an XivelyClientString: Send strings to
array. xively.com.
While Loop: How to use a while loop to BarometricPressureWebServer: Outputs the
calibrate a sensor while a button is being values from a barometric pressure sensor as
read. a web page.
Switch Case: How to choose between a UDPSendReceiveString: Send and receive
discrete number of values. Equivalent to text strings via UDP.
multiple If statements. This example shows UdpNtpClient: Query a Network Time
how to divide a sensor's range into a set of Protocol (NTP) server using UDP.
four bands and to take four different actions DnsWebClient: DNS and DHCP-based
depending on which band the result is in. Web client.
Switch Case 2: A second switch-case DhcpChatServer: A simple DHCP Chat
example, showing how to take different Server.
actions based in characters received in the DhcpAddressPrinter: Get an IP address via
serial port. DHCP and print it out.
TelnetClient: A simple Telnet client.
6.Sensors
Firmata Libraries
ADXL3xx: Read an ADXL3xx
accelerometer. Guide to the Standard Firmata Library
Knock: Detect knocks with a piezo
element. GSM Library
Memsic2125 : Two-axis acceleromoter.
Ping: Detecting objects with an ultrasonic GSM Examples
range finder. Make Voice Call: Get your shield to make
phone calls from the Serial Monitor.
7.Display Receive Voice Call: Check the status of the
modem while getting voice calls.
Examples of basic display control Send SMS: Use the Serial Monitor to type
in SMS messages to different phone
LED Bar Graph: How to make an LED bar numbers.
graph. Receive SMS: Read SMS messages and
Row Column Scanning: How to control an prompt them to the Serial Monitor.
8x8 matrix of LEDs. Web Client: Download the content of a
website to your Arduino board through
8.Strings GPRS.
Web Server: Create a wireless web server
StringAdditionOperator: Add strings through GPRS.
together in a variety of ways. Xively Client: Communicate to the Xively
StringAppendOperator: Append data to sensor backbone.
strings. Xively Client String: Communicate to the
StringCaseChanges: Change the case of a Xively sensor backbone.
string.
StringCharacters: Get/set the value of a GSM Tools
specific character in a string.
StringComparisonOperators: Compare Test Modem: Read the IMEI of your
strings alphabetically. modem.
StringConstructors: How to initialize string Test GPRS: Test the proper functionality of
objects. the GPRS network using your SIM card.
StringIndexOf: Look for the first/last GSM Scan Networks: Check for the
instance of a character in a string. available networks.
StringLength & StringLengthTrim: Get and Pin Management: Manage the PIN number
trim the length of a string. of your SIM card.
StringReplace: Replace individual Band Management: Manage the band the
characters in a string. GSM shield connects to.
StringStartsWithEndsWith: Check which Test Web Server: Create a webserver with
characters/substrings a given string starts or your GSM shield.
ends with.
StringSubstring: Look for "phrases" within LiquidCrystal Library
a given string.
Hello World: Displays "hello world!" and
9.USB (Leonardo, Micro, and Due specific the seconds since reset.
examples) Blink: Control of the block-style cursor.
Cursor: Control of the underscore-style
The Keyboard and Mouse examples are unique to cursor.
the Leonardo, Micro and Due. They demonstrate Display: Quickly blank the display without
the use of libraries that are unique to the board. losing what's on it.
TextDirection: Control which way text
KeyboardAndMouseControl: Demonstrates flows from the cursor.
the Mouse and Keyboard commands in one Scroll: Scroll text left and right.
program. Serial input: Accepts serial input, displays
it.
Keyboard SetCursor: Set the cursor position.
Autoscroll: Shift text right and left.
KeyboardMessage: Sends a text string
when a button is pressed. Robot Library
KeyboardLogout : Logs out the current user
with key commands. Logo - Tell your robot where to go through
KeyboardSerial: Reads a byte from the the on-board keyboard.
serial port, and sends back a keystroke. Line Following - Draw a racing track and
KeyboardReprogram : Opens a new get your robot to run on it.
window in the Arduino IDE and Disco Bot - Turn your robot into an 8-bit
reprograms the Leonardo with a simple jukebox and dance to the beat.
blink program. Compass - Plan a treasure hunt with this
digital compass.
Mouse Inputs - Learn how to control the knob and
the keyboard.
ButtonMouseControl: Control cursor Wheel Calibration - Tune the wheels to
movement with 5 pushbuttons. perform even better.
JoystickMouseControl: Controls a Runaway Robot - Play tag with your robot
computer's cursor movement with a using a distance sensor.
Joystick when a button is pressed. Remote control - Reuse that old tv-remote
to command the bot on distance.
Picture browser - Want to use your own
images? This is how.
Rescue - Train your robot to look for
hidden pearls in a maze.
Hello User - Hack the robot's welcome
demo and make your own.
SPI Library
BarometricPressureSensor: Read air
pressure and temperature from a sensor
using the SPI protocol.
SPIDigitalPot: Control a AD5206 digital
potentiometer using the SPI protocol.
Servo Library
Knob: Control the shaft of a servo motor by
turning a potentiometer.
Sweep: Sweeps the shaft of a servo motor
back and forth.
Software Serial Library
Software Serial Example: How to use the
SoftwareSerial Library...Because
sometimes one serial port just isn't enough!
Two Port Receive: How to work with
multiple software serial ports.
Stepper Library
Motor Knob: Control a highly accurate
stepper motor using a potentiometer.
TFT Library
Esplora
Esplora TFT Bitmap Logo: Read an image
file from a micro-SD card and draw it at
random locations.
Esplora TFT Color Picker: Using the
joystick and slider, change the color of the
TFT screen.
Esplora TFT Etch a Sketch: An Esplora
implementation of the classic Etch-a-
Sketch.
Esplora TFT Graph: Graph the values from
the light sensor to the TFT.
Esplora TFT Horizon: Draw an artificial
horizon line based on the tilt from the
accelerometer.
Esplora TFT Pong: A basic implementation
of the classic game.
Esplora TFT Temperature: Check the
temperature with the onboard sensor and
display it on screen.
Arduino
TFT Bitmap Logo: Read an image file from
a micro-SD card and draw it at random
locations.
TFT Display Text : Read the value of a
sensor and print it on the screen.
TFT Pong: An Arduino implementation of
the classic game.
Etch a Sketch: An Arduino version of the
classic Etch-a-Sketch.
Color Picker: With three sensors, change
the color of the TFT screen.
Graph: Graph the values from a variable
resistor to the TFT.
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.
master reader/slave sender: Set up two (or
more) arduino boards to share information
via a master reader/slave sender
configuration.
master writer/slave reader: Allow two (or
more) arduino boards to share information
using a master writer/slave reader set up.
WiFi 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
ScanNetworks : Displays all WiFi networks
in range
WiFiChatServer : Set up a simple chat
server
WiFiXivelyClient : connect to xively.com,
a free datalogging site
WiFiXivelyClientString: send strings to
xively.com
WiFiWebClient : Connect to a remote
webserver
WiFiWebClientRepeating: Repeatedly
make HTTP calls to a server
WiFiWebServer : Serve a webpage from
the WiFi shield
Arduino as ISP Programmer
ArduinoISP Turns your Arduino into an in-circuit
programmer to re-program Atmega chips. Useful
when you need to re-load the bootloader on an
Arduino, if you're going from Arduino to an
Atmega on a breadboard, or if you're making your
own Arduino-compatible circuit on a breadboard.
More
For a huge list of examples from the Arduino
community, see the interfacing with hardware page
on the playground wiki. Also see the list of old
examples.
Writing examples
Here's a style guide that helps with writing
examples for beginners.