You are on page 1of 36

UNIVERSIDAD NACIONAL DEL CENTRO DEL

PER
CURSO DE ROBOTICA NIVEL I
1. Principios de Electrnica y Ejemplo N 1
2. Ejemplo N 2 y Practica N 1
3. Introduccin a la Robtica y Ejemplo N 3
4. Ejemplo N 4 y Practica N 2
5. Tarjetas de Programacin y Ejemplo N 5
6. Ejemplo N 6 y Practica N 3
7. Arquitectura de Microcontroladores y Ejemplo N 7
8. Ejemplo N 8 y Practica N 4
9. Fundamentos de Programacin y Ejemplo N 9
10. Ejemplo N 10 y Practica N 5
11. Sensores y Actuadores y Ejemplo N 11
12. Ejemplo N 12 y Practica N 6

Ejemplo 1:
/*
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); // wait for a second
}


Ejemplo 2:
/*
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
}

Ejemplo 3:
/*
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
}


Ejemplo 4:
/*
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);
}

Ejemplo 5:
/*
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);
}
Ejemplo 6:
/* 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; // ledState used to set the LED
long previousMillis = 0; // will store last time LED was updated

// the follow variables is a long because the time, measured in
miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000; // interval at which to blink
(milliseconds)

void setup() {
// set the digital pin as output:
pinMode(ledPin, OUTPUT);
}

void loop()
{
// here is where you'd put code that needs to be running all the time.

// check to see if it's time to blink the LED; that is, if the
// difference between the current time and last time you blinked
// the LED is bigger than the interval at which you want to
// blink the LED.
unsigned long currentMillis = millis();

if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;

// if the LED is off turn it on and vice-versa:
if (ledState == LOW)
ledState = HIGH;
else
ledState = LOW;

// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
}
}

Ejemplo 7:
/*
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);
}
}

Ejemplo 8:
/*
State change detection (edge detection)

Often, you don't need to know the state of a digital input all the time,
but you just need to know when the input changes from one state to another.
For example, you want to know when a button goes from OFF to ON. This is called
state change detection, or edge detection.

This example shows how to detect when a button or button changes from off to on
and on to off.

The circuit:
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
* LED attached from pin 13 to ground (or use the built-in LED on
most Arduino boards)

created 27 Sep 2005
modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

http://arduino.cc/en/Tutorial/ButtonStateChange

*/

// this constant won't change:
const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to

// Variables will change:
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button

void setup() {
// initialize the button pin as a input:
pinMode(buttonPin, INPUT);
// initialize the LED as an output:
pinMode(ledPin, OUTPUT);
// initialize serial communication:
Serial.begin(9600);
}


void loop() {
// read the pushbutton input pin:
buttonState = digitalRead(buttonPin);

// compare the buttonState to its previous state
if (buttonState != lastButtonState) {
// if the state has changed, increment the counter
if (buttonState == HIGH) {
// if the current state is HIGH then the button
// wend from off to on:
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter);
}
else {
// if the current state is LOW then the button
// wend from on to off:
Serial.println("off");
}
}
// save the current state as the last state,
//for next time through the loop
lastButtonState = buttonState;


// turns on the LED every four button pushes by
// checking the modulo of the button push counter.
// the modulo function gives you the remainder of
// the division of two numbers:
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}

}

Ejemplo 9:

/*
Input Pullup Serial

This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a
digital input on pin 2 and prints the results to the serial monitor.

The circuit:
* Momentary switch attached from pin 2 to ground
* Built-in LED on pin 13

Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal
20K-ohm resistor is pulled to 5V. This configuration causes the input to
read HIGH when the switch is open, and LOW when it is closed.

created 14 March 2012
by Scott Fitzgerald

http://www.arduino.cc/en/Tutorial/InputPullupSerial

This example code is in the public domain

*/

void setup(){
//start serial connection
Serial.begin(9600);
//configure pin2 as an input and enable the internal pull-up resistor
pinMode(2, INPUT_PULLUP);
pinMode(13, OUTPUT);

}

void loop(){
//read the pushbutton value into a variable
int sensorVal = digitalRead(2);
//print out the value of the pushbutton
Serial.println(sensorVal);

// Keep in mind the pullup means the pushbutton's
// logic is inverted. It goes HIGH when it's open,
// and LOW when it's pressed. Turn on pin 13 when the
// button's pressed, and off when it's not:
if (sensorVal == HIGH) {
digitalWrite(13, LOW);
}
else {
digitalWrite(13, HIGH);
}
}

Ejemplo 10:

/*
Melody

Plays a melody

circuit:
* 8-ohm speaker on digital pin 8

created 21 Jan 2010
modified 30 Aug 2011
by Tom Igoe

This example code is in the public domain.

http://arduino.cc/en/Tutorial/Tone

*/
#include "pitches.h"

// notes in the melody:
int melody[] = {
NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3,0, NOTE_B3, NOTE_C4};

// note durations: 4 = quarter note, 8 = eighth note, etc.:
int noteDurations[] = {
4, 8, 8, 4,4,4,4,4 };

void setup() {
// iterate over the notes of the melody:
for (int thisNote = 0; thisNote < 8; thisNote++) {

// to calculate the note duration, take one second
// divided by the note type.
//e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
int noteDuration = 1000/noteDurations[thisNote];
tone(8, melody[thisNote],noteDuration);

// to distinguish the notes, set a minimum time between them.
// the note's duration + 30% seems to work well:
int pauseBetweenNotes = noteDuration * 1.30;
delay(pauseBetweenNotes);
// stop the tone playing:
noTone(8);
}
}

void loop() {
// no need to repeat the melody.
}

Ejemplo 11:
/*
Analog input, analog output, serial output

Reads an analog input pin, maps the result to a range from 0 to 255
and uses the result to set the pulsewidth modulation (PWM) of an output pin.
Also prints the results to the serial monitor.

The circuit:
* potentiometer connected to analog pin 0.
Center pin of the potentiometer goes to the analog pin.
side pins of the potentiometer go to +5V and ground
* LED connected from digital pin 9 to ground

created 29 Dec. 2008
modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

// These constants won't change. They're used to give names
// to the pins used:
const int analogInPin = A0; // Analog input pin that the potentiometer is
attached to
const int analogOutPin = 9; // Analog output pin that the LED is attached to

int sensorValue = 0; // value read from the pot
int outputValue = 0; // value output to the PWM (analog out)

void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}

void loop() {
// read the analog in value:
sensorValue = analogRead(analogInPin);
// map it to the range of the analog out:
outputValue = map(sensorValue, 0, 1023, 0, 255);
// change the analog out value:
analogWrite(analogOutPin, outputValue);

// print the results to the serial monitor:
Serial.print("sensor = " );
Serial.print(sensorValue);
Serial.print("\t output = ");
Serial.println(outputValue);

// wait 2 milliseconds before the next loop
// for the analog-to-digital converter to settle
// after the last reading:
delay(2);
}

Ejemplo 12:
/*
Analog Input
Demonstrates analog input by reading an analog sensor on analog pin 0 and
turning on and off a light emitting diode(LED) connected to digital pin 13.
The amount of time the LED will be on and off depends on
the value obtained by analogRead().

The circuit:
* Potentiometer attached to analog input 0
* center pin of the potentiometer to the analog pin
* one side pin (either one) to ground
* the other side pin to +5V
* LED anode (long leg) attached to digital output 13
* LED cathode (short leg) attached to ground

* Note: because most Arduinos have a built-in LED attached
to pin 13 on the board, the LED is optional.


Created by David Cuartielles
modified 30 Aug 2011
By Tom Igoe

This example code is in the public domain.

http://arduino.cc/en/Tutorial/AnalogInput

*/

int sensorPin = A0; // select the input pin for the potentiometer
int ledPin = 13; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor

void setup() {
// declare the ledPin as an OUTPUT:
pinMode(ledPin, OUTPUT);
}

void loop() {
// read the value from the sensor:
sensorValue = analogRead(sensorPin);
// turn the ledPin on
digitalWrite(ledPin, HIGH);
// stop the program for <sensorValue> milliseconds:
delay(sensorValue);
// turn the ledPin off:
digitalWrite(ledPin, LOW);
// stop the program for for <sensorValue> milliseconds:
delay(sensorValue);
}





RESUMEN
ARDUINO, PLATAFORMA DE HARDWARE LIBRE
Arduino es una plataforma de hardware libre, basada en una placa con un microcontrolador
y un entorno de desarrollo, diseada para facilitar el uso de la electrnica en proyectos
multidisciplinares.
El hardware consiste en una placa con un microcontrolador Atmel AVR y puertos de
entrada/salida. Los microcontroladores ms usados son el Atmega168, Atmega328,
Atmega1280, ATmega8 por su sencillez y bajo coste que permiten el desarrollo de
mltiples diseos. Por otro lado el software consiste en un entorno de desarrollo que
implementa el lenguaje de programacin Processing/Wiring y el cargador de arranque
(boot loader) que corre en la placa.
Arduino se puede utilizar para desarrollar objetos interactivos autnomos o puede ser
conectado a software del ordenador (por ejemplo: Macromedia Flash, Processing,
Max/MSP, Pure Data). Las placas se pueden montar a mano o adquirirse. El entorno de
desarrollo integrado libre se puede descargar gratuitamente.
Al ser open-hardware, tanto su diseo como su distribucin es libre. Es decir, puede
utilizarse libremente para el desarrollo de cualquier tipo de proyecto sin haber adquirido
ninguna licencia.
Consta de 14 entradas digitales configurables entrada i/o que operan a 5 voltios. Cada pin
puede proporcionar o recibir como mximo 40 mA. Los pines 3, 5, 6, 8, 10 y 11 pueden
proporcionar una salida PWM (Pulse Width Modulation). Si se conecta cualquier cosa a
los pines 0 y 1, eso interferir con la comunicacin USB. Diecimila tambin tiene 6
entradas analgicas que proporcionan una resolucin de 10 bits. Por defecto miden de 0
voltios (masa) hasta 5 voltios, aunque es posible cambiar el nivel ms alto, utilizando el
pin Aref y algn cdigo de bajo nivel.
Existen numerosos modelos de Arduino con direferentes tamaos y caractersticas:
Arduino UNO, Duemilanove (Nano), Mega 2560, ATmega1280, Mini, Fio, BT w/
ATmega328, BT w/ ATmega168, LilyPad Arduino w/ ATmega328, LilyPad Arduino w/
ATmega168, Pro, Pro Mini, NG, etc.
Mostramos una foto de Arduino, en concreto del modelo UNO, en una mano para apreciar
la escala:

Vista en detalle de Arduino UNO en su parte superior:

Frontal del Arduino UNO (conector USB y alimentacin elctrica):

Parte trasera del Arduino UNO:

Algunos sensores que se pueden conectar a Arduino: temperatura, humedad, baromtrico,
acelermetro, alcoholmetro, infrarojos, comps, giroscopio, capacitivo, corriente,
distancia, fuerza, movimiento, proximidad, ptico, sonido, etc.

Por supuesto, tambin se le pueden conectar a Arduino una serie de mdulos para dotarlo
de funcionalidades extra como: mdem GPRS (conectando una tarjeta SIM podremos
enviar SMS, hacer llamadas y conectarnos a Internet desde Arduino), Ethernet Shield (para
conectar Arduino a una red LAN), mdulo Bluetooth, mdulo GPS, control de rels, RGB
LED, pantalla OLED, conectividad Wifi, sintonizador digital FM, etc.
En la imagen un mdulo GPRS Quadband:

La parte de atrs del mdulo GPRS acoplable para Arduino UNO:

Conectar Arduino UNO a un PC con W7, instalar y configurar Arduino IDE
Adquisicin del hardware necesario: Arduino UNO, cable USB tipo A-B y LED
Como ejemplo en este artculo conectaremos Arduino UNO a un PC con cable USB y
enviaremos un programa a Arduino para que encienda un LED. A continuacin indicamos
el hardware necesario para realizar este proyecto de ejemplo.
En primer lugar necesitaremos, obviamente, adquirir el Arduino UNO, lo podremos
adquirir va web en cualquier proveedor, por ejemplo desde http://www.cooking-
hacks.com (Libelium Comunicaciones Distribuidas S.L.). En concreto, Arduino UNO
cuesta unos 22,00 euros:

Por otro lado, para este proyecto hardware de ejemplo con Arduino UNO usaremos
un LED que cuesta unos 0,20 euros:

Para la conexin del Arduino UNO con el PC usaremos un cable USB de tipo A-B:

Si no usramos el pin digital 13 de Arduino para conectar el LED necesitaramos
una resistencia de unos 200 ohmios (el valor estndar ms cercano es de 220 ohmios), el
clculo:
Un LED normal necesita de entre 5 y 20 mA para encenderse, por lo que necesitaremos
unos 15mA para que el LED luzca bien.
La alimentacin del Arduino UNO es de 5 voltios.
En el LED caern 2 voltios.
En la resistencia deben caer unos 3 voltios.
Por lo tanto:
5 - 2 = 3 voltios de tensin
Aplicando la ley de Ohm (Tensin = Intensidad * Resistencia):
V = I * R
Puesto que conocemos V e I podremos calcular R:
R = V / I
Con los valores:
R = 3 / 0.015 = 200 ohmios
(donde "0.015" sern los 15mA que necesita el LED pasados a amperios)
Por lo tanto necesitaremos la resistencia del mercado que ms se aproxime a 200 ohmios,
que es una de 220 ohmios:

La resistencia ira conectada a la pata ms larga del LED, la positiva (ctodo), algo as:

Pero en nuestro caso no usaremos una resistencia externa pues conectaremos el LED al pin
digital 13 de Arduino que ya incorpora en placa dicha resistencia:

Instalacin software IDE de desarrollo y controladores para conectar Arduino con un PC
con Windows 7
Para poder programar el Arduino UNO usaremos el propio IDE que proporciona Arduino,
podremos descargar la ltima versin desde:
http://arduino.cc/en/Main/Software
Actualmente podremos descargar la versin 0022 de Arduino IDE, para el caso de
Windows el fichero arduino-0022.zip de 86 MB. Descomprimiremos el fichero descargado
en una carpeta. Esta carpeta contiene tanto el IDE de desarrollo de Arduino como los
drivers (controladores) para la conexin USB en Windows.
Tras descargar el fichero y descomprimirlo, en el caso de Linux no ser necesario instalar
drivers, pero en el caso de Microsoft Windows 7 deberemos instalar los controladores para
el emulador de puerto USB a puerto serie. Aunque Arduino se conecta al PC mediante el
puerto USB en realidad, internamente, emula un puerto serie, por ello, en Microsoft
Windows 7 realizaremos los siguientes pasos para instalar los drivers:
1. Conectaremos Arduino UNO al PC mediante el cable USB de tipo A-B:

2. Microsoft Windows 7 detectar el dispositivo e intentar instalar los drivers:

3. No encontrar los drivers, por lo que dar error. No ser problema, lo ignoraremos:

4. Accederemos al botn "Inicio" - "Panel de control":

5. Pulsaremos en "Hardware y sonido":

6. Pulsaremos en "Administrador de dispositivos":

7. En la ventana del Administrador de dispositivos, en "Otros dispositivos" nos mostrar
con admiracin "Arduino Uno", pulsaremos con el botn derecho del ratn y
seleccionaremos "Actualizar software de controlador":

8. Pulsaremos en "Buscar software de controlador en el equipo. Buscar e instalar el
software de controlador de forma manual":

9. Pulsaremos en el botn "Examinar" para seleccionar la carpeta donde se encuentran los
drivers:

10. Seleccionaremos la carpeta "arduino-0022" (descomprimida anteriormente) y, dentro
de esta, la carpeta "drivers":

11. Pulsaremos "Siguiente":

12. El asistente para instalar un nuevo controlador nos mostrar un aviso de seguridad,
pulsaremos "Instalar este software de controlador de todas formas":

13. Si todo es correcto, el asistente nos habr instalado el controlador para Arduino UNO y
nos mostrar la siguiente ventana:

14. En el Administrador de dispositivos de Microsoft Windows 7 nos mostrar el nuevo
controlador instalado, en "Puertos (COM y LPT)". Es importante que anotemos el nombre
asignado al puerto COM para Arduino, en nuestro caso COM3, pues lo necesitaremos
seleccionar en el IDE de Arduino:

Primera ejecucin del IDE de Arduino y configuracin inicial para desarrollar proyectos
hardware
Tras instalar el controlador de Arduino, ahora realizaremos una primera ejecucin para
configurar el IDE de desarrollo, pulsaremos con el botn derecho del ratn sobre el
ejecutable "arduino.exe" de la carpeta descomprimida anteriormente y seleccionaremos
"Ejecutar como administrador" (no es necesario, pero as evitamos posibles problemas de
limitaciones deMicrosoft Windows 7):

En el IDE de desarrollo de Arduino, en primer lugar seleccionaremos el tipo de dispositivo
(Board). Para ello pulsaremos en el men "Tools" - "Board" y seleccionaremos "Arduino
Uno" (o el que hayamos adquirido):

Seleccionaremos tambin el puerto serie asignado al controlador de Arduino (en nuestro
caso COM3), para ello accederemos al men "Tools" - "Serial Port" - "COM3":

Primer proyecto hardware con Arduino UNO, encender un LED
Una vez adquirido Arduino, conectado al PC y configurado el IDE, vamos a explicar cmo
realizar una primera aplicacin en Arduino IDE y cmo enviarla al dispositivo y testearla.
Como ya hemos comentado encenderemos un LED, si no disponemos de un LED no es
problema pues la placa de Arduino UNO incorpora un LED que nos servira para las
pruebas:

Si disponemos de un LED conectaremos la pata ms larga (positivo ctodo) al ping
digital 13 de Arduino y la pata ms corta al ping GND ms cercano al 13:

El LED quedar conectado directamente a los conectores del Arduino, lo ms profesional
es usar una placa prototipo y conectar ah el LED y, a su vez, conectar la placa prototipo al
Arduino con sus cables correspondientes.
El LED conectado directamente al Arduino:

Con una placa prototipo y usando una resistencia sera algo as:

Pero, repetimos, para realizar un ejemplo bsico no es necesaria ni la resistencia, ni la
placa prototipo o incluso ni el LED, pues Arduino UNO ya incorpora una resistencia en el
ping 13 y un LED incorporado en placa.
Abriremos el IDE de desarrollo de Arduino, abriremos una aplicacin de ejemplo que
incluye el propio Arduino para encender y apagar un LED, para ello accederemos al men
"File" - "Examples" - "Basics" - "Blink":

Se abrir el siguiente programa, cada lnea est comentada explicando para qu sirve:
/*
Blink
Turns on an LED on for one second, then off for one second, repeatedly.

This example code is in the public domain.
*/

void setup() {
// initialize the digital pin as an output.
// Pin 13 has an LED connected on most Arduino boards:
pinMode(13, OUTPUT);
}

void loop() {
digitalWrite(13, HIGH); // set the LED on
delay(1000); // wait for a second
digitalWrite(13, LOW); // set the LED off
delay(1000); // wait for a second
}
Pulsaremos en el botn "Verify" para compilar el cdigo C++ y verificar que es correcto:

En la parte inferior indicar si la compilacin ha sido correcta con "Done compiling" o si
ha habido algn error (en cuyo caso no podremos enviarlo a Arduino):

Para enviar el programa al dispositivo Arduino conectado al PC y probarlo directamente
pulsaremos en el botn "Upload":

Si el envo por el puerto establecido se ha realizado correctamente al dispositivo Arduino,
en la parte inferior mostrar "Done uploading":

Si todo es correcto, cada segundo se encender el LED y se apagar otro segundo, as
sucesivamente pues hemos usado un "loop":

Alimentacin elctrica para Arduino UNO
En el proyecto de ejemplo que hemos realizado hemos alimentado el Arduino mediante el
cable USB conectado al PC, obviamente, si desconectamos este cable el Arduino se
apagar. Para alimentarlo sin PC necesitaremos un adaptador de +12V con un conector
como el que se muestra en la imagen:

Conectndolo a la corriente elctrica y al Arduino el programa que hemos cargado se
iniciar y se encender y apagar el LED, esto es debido a que Arduino cuenta con una
memoria para alojar el programa enviado y as poder ejecutarlo cuando se enciende (si as
se ha programado):

Por supuesto, Arduino puede ser alimentado elctrimante de muchas otras formas, por
ejemplo con placas solares y una batera:

En esta imagen mostramos el LED funcionando con dos placas solares conectadas en serie
y, a su vez, conectadas al Arduino en su conector de alimentacin elctrica:

You might also like