0% found this document useful (0 votes)
65 views31 pages

Ejemplo S

This document provides instructions for blinking an LED using an Arduino board. It explains how to connect an LED and resistor to pin 13 of the Arduino, and provides the code to turn the LED on and off to make it blink. The code uses pinMode(), digitalWrite(), and delay() functions to initialize pin 13 as an output, set it high or low to turn the LED on or off, and add delays between the on and off states to make the LED blink. Connecting an LED in this simple circuit and running this code demonstrates a basic physical output from an Arduino microcontroller.

Uploaded by

Wilzon Chambi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views31 pages

Ejemplo S

This document provides instructions for blinking an LED using an Arduino board. It explains how to connect an LED and resistor to pin 13 of the Arduino, and provides the code to turn the LED on and off to make it blink. The code uses pinMode(), digitalWrite(), and delay() functions to initialize pin 13 as an output, set it high or low to turn the LED on or off, and add delays between the on and off states to make the LED blink. Connecting an LED in this simple circuit and running this code demonstrates a basic physical output from an Arduino microcontroller.

Uploaded by

Wilzon Chambi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Learning Examples | Foundations | Hacking | Links

Examples > Basics


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

Resistor, anything between 220 ohm to 1K ohm

Circuit

To build the circuit, connect one end of the resistor to Arduino pin 13. Connect the long leg
of the LED (the positive leg, called the anode) to the other end of the resistor. Connect the
short leg of the LED (the negative leg, called the cathode) to the Arduino GND, as shown
in the diagram and the schematic 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.
click the image to enlarge

image developed using Fritzing. For more circuit examples, see the Fritzing project page

Schematic
click the image to enlarge

After you build the circuit plug your Arduino board into your computer, start the Arduino
IDE, and enter the code below.
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);
// wait for a second
}

Ejemplos > Libraras > LiquidCrystal

LiquidCrystal
La librera LiquidCrystal te permite controlar displays LCD que sean complatibles con el
driver Hitachi HD44780. Hay muchos de ellos ah fuera, y puedes comunicarte con ellos a
travs del interfaz de 16 pines.
Este sketch de ejemplo imprime "Hello World!" en el LCD y muestra el tiempo en
segundos desde que Arduino fu reseteado por ltima vez.

salida del sketch en un LCD de 2x16


El LCD tiene un interfaz paralelo, significando esto que el microcontrolador tiene que
manipular varios pines del interfaz a la vez para controlarlo. El interfaz consta de los
siguientes pines:
Un pin de seleccin de registro (RS) que controla en qu parte de la memoria del LCD
ests escribiendo datos. Puedes seleccionar bien el regisro de datos, que mantiene lo que
sale en la pantalla, o un registro de instruccin, que es donde el controlador del LCD busca
las instrucciones para saber cual es lo siguiente que hay que hacer.
El pin de lectura/escritura (R/W)que selecciona el modo de lectura o el de escritura.
Un pin para habilitar (enable) que habilita los registros.

8 pines de datos (D00-D07). Los estados de estos pines (nivel alto o bajo) son los bits que
ests escribiendo a un registro cuando escribes, o los valores de lectura cuando ests
leyendo.
Hay tambin un pin de contraste del display (Vo), pines de alimentacin (+5V y GND) y
pines de retro-iluminacin (Bklt+ y Bklt-), que te permiten alimentar el LCD, controlar el
contraste del display, o encender y apagar la retro-iluminacin, respectivamente.
El proceso de controlar el display involucra la colocacin de los datos que componen la
imagen de lo que quieres mostrar, en los registros de datos, y luego, colocar las
instrucciones, en el registro de instrucciones. La librera LiquidCrystal te simplifica todo
este proceso de forma que no neesitas saber las instrucciones de bajo nivel.
Los LCD-s compatibles con Hitachi pueden ser controlados de dos modos: 4 bits u 8 bits.
El modo de 4 bits requiere siete pines de E/S de Arduino, mientras el modo de 8 bits
requiere 11 pines. Para mostrar texto en la pantalla, puedes hacer la mayora de las cosas en
modo 4 bits, por lo que el ejemplo muestra como controlar un LCD de 2x16 en modo de 4
bits.
NOTA: La librera LiquidCrystal tiene revisiones venidas a menos despus de la
versin 0016 de Arduino. Gracias a Limor Fried por reescribirla para incluir los modos de
4 y 8 bits y otras funcionalidades. Estas notas hacen referencia a la versin actual como es
Arduino 0017.

Otros ejemplos de la librera LiquidCrystal

Hello World - muestra "hello world!" y los segundos desde el ltio reset

Blink - control del cursor en forma de bloque.

Cursor - control del cursor en forma de guin bajo.

Display - limpieza rpida del display, sin perder lo que haba en l.

Text Direction - controla en qu sentido fluye el texto desde el cursor.

Autoscroll - scroll automtico del nuevo texto.

Serial input - acepta la entrada serie y la muestra.

SetCursor - establece la posicin del cursor.

Scroll - realiza un scroll del texto a la izquierda y a la derecha

Circuito

El pin RS del LCD conectado a la E/S digital en el pin 12

El pin enable del LCD conectado a la E/S digital en el pin 11.

Los pines D4 - D7 conectado a las E/S digitales desde el pin 5 hasta el 2.

Los pines de voltaje y tierra conectados a +5V y tierra.

El pin Vo, que controla el constraste, conectado a un potencimetro. Ajusta el


potencimetro para que el texto tenga el contraste que t quieras.

Nota: Este diagrama de wiring es diferente que el que haba en anteriores versiones la de
librera LiquidCrystal. Los pines de R/W (lectura/escritura) estn conectado a tierra, y el
pin de enable se mueve al pin 11, liberando el pin E/S para otros usos.
pincha en la imagen para aumentarla

Programa
/*
LiquidCrystal Library - Hello World
Demonstrates the use a 16x2 LCD display. The LiquidCrystal
library works with all LCD displays that are compatible with the
Hitachi HD44780 driver. There are many of them out there, and you
can usually tell them by the 16-pin interface.
This sketch prints "Hello World!" to the LCD
and shows the time.
The circuit:
LCD RS pin to digital pin 12
LCD Enable pin to digital pin 11
LCD D4 pin to digital pin 5
LCD D5 pin to digital pin 4
LCD D6 pin to digital pin 3
LCD D7 pin to digital pin 2
10K resistor:
ends to +5V and ground
wiper to LCD VO pin (pin 3)

*
*
*
*
*
*
*
*
*

Library originally added 18 Apr 2008


by David A. Mellis
library modified 5 Jul 2009
by Limor Fried (http://www.ladyada.net)
example added 9 Jul 2009
by Tom Igoe

modified 8 Feb 2010


by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print a message to the LCD.
lcd.print("hello, world!");
}
void loop() {
// set the cursor to column 0, line 1
// (note: line 1 is the second row, since counting begins with 0):
lcd.setCursor(0, 1);
// print the number of seconds since reset:
lcd.print(millis()/1000);
}

Arrays
This variation on the For Loop example shows how to use an array. An array is a variable
with multiple parts. If you think of a variable as a cup that holds values, you might think of
an array as an ice cube tray. It's like a series of linked cups, all of which can hold the same
maximum value.
The For Loop example shows you how to light up a series of LEDs attached to pins 2
through 7 of the Arduino, with certain limitations (the pins have to be numbered
contiguously, and the LEDs have to be turned on in sequence).
This example shows you how you can turn on a sequence of pins whose numbers are
neither contiguous nor necessarily sequential. To do this is, you can put the pin numbers in
an array and then use for loops to iterate over the array.
This example makes use of 6 LEDs connected to the pins 2 - 7 on the board using 220 Ohm
resistors, just like in the For Loop. However, here the order of the LEDs is determined by
their order in the array, not by their physical order.
This technique of putting the pins in an array is very handy. You don't have to have the pins
sequential to one another, or even in the same order. You can rearrange them however you
want.

Hardware Required

Arduino Board

(6) 220 ohm resistors

(6) LEDs

hook-up wire

breadboard

Circuit
Connect six LEDS, with 220 ohm resistors in series, to digital pins 2-7 on your Arduino.
click the image to enlarge

image developed using Fritzing. For more circuit examples, see the Fritzing project page

Schematic:
click the image to enlarge

Code
/*
Arrays
Demonstrates the use of an array to hold pin numbers
in order to iterate over the pins in a sequence.
Lights multiple LEDs in sequence, then in reverse.
Unlike the For Loop tutorial, where the pins have to be

contiguous, here the pins can be in any random order.


The circuit:
* LEDs from pins 2 through 7 to ground
created 2006
by David A. Mellis
modified 30 Aug 2011
by Tom Igoe
This example code is in the public domain.
http://www.arduino.cc/en/Tutorial/Array
*/
int timer = 100;
int ledPins[] = {
2, 7, 4, 6, 5, 3 };
int pinCount = 6;

// The higher the number, the slower the timing.


// an array of pin numbers to which LEDs are attached
// the number of pins (i.e. the length of the array)

void setup() {
// the array elements are numbered from 0 to (pinCount - 1).
// use a for loop to initialize each pin as an output:
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
pinMode(ledPins[thisPin], OUTPUT);
}
}
void loop() {
// loop from the lowest pin to the highest:
for (int thisPin = 0; thisPin < pinCount; thisPin++) {
// turn the pin on:
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
// turn the pin off:
digitalWrite(ledPins[thisPin], LOW);
}
// loop from the highest pin to the lowest:
for (int thisPin = pinCount - 1; thisPin >= 0; thisPin--) {
// turn the pin on:
digitalWrite(ledPins[thisPin], HIGH);
delay(timer);
// turn the pin off:
digitalWrite(ledPins[thisPin], LOW);

}
}

Secuencia de Leds con Arduino


Publicado: febrero 10, 2012 en Arduino
Etiquetas:Arduino, led, microprocesador, open hardware

Hace un tiempo compre una placa de Arduino pero por falta de tiempo, haba hecho
algunos ejemplos pero quera al menos documentar como funciona de una manera sencilla
(para dummies), ademas que acabando de cursar una materia de la Universidad llamada
Microprocesadores en la cual se aprendi bastante pero tambin miraba que todo lo
que hacamos en las prcticas se me facilitara la vida si usara mi placa de Arduino (adems
que aunque los pics son baratos tocaba comprar quemador de pics) y bueno de ahi surgo
este pequeo ejemplo, espero que les guste y cualquier cosa no duden en preguntar o
colaborar en el aprendizaje de esta gran placa.
Materiales
1 Placa de arduino
1 Protoboard
8 Leds (cualquier color)
8 resistencias de 220
1 resistencia de 1 K
1 pulsador
Cable Utp
1 El programa consiste en que al presionar el pulsador los leds cambien de secuencia, las
secuencias son las siguientes (1) Leds Encendidos (0) Leds apagado:
a)
00000001
00000010
00000100
.
.
10000000

b)
00011000
00111100
01111110
11111111
c)
00000001
00000011
00000111
.
.
11111111
d)
00001111
11110000
.
.
2. Como sabemos los leds tiene un anodo (+) y un catodo (-), de un lado conectaremos
todos los Catodos a las resistencias de 220 y estas a GND y de los anodos conectaremos
a los pines del 2 al 9, las resistencias se colocan con el fin que no quemar los leds.
3. Conectamos el pulsador de la siguiente manera de un lado a 5V y del otro conectamos
una resistencia a tierra y tambien un cable al pin A0 que sera el que nos permita cambiar de
secuencia cada vez que lo presionemos, Se coloca la resistencia de 1 k porque haria un
puente entre GND y el pin A0 de esta manera la lectura de entrada sera siempre 0, al
presionar el pulsador lo que hace es hacer puente entre 5V y A0, de esta manera
conseguimos el valor de 1 con esto los valores de entrada unicamente seran 1 y 0.
Aqu muestro el montaje realizado en un software llamado Fritzing V 0.7.0 de licencia
GNU GPL v3 el cual lo pueden conseguir en http://www.fritzing.org

int saltar=0; // Variable que indica el numero de la secuencia a


ejecutarse
void setup() {
pinMode(A0, INPUT); //indicamos el pin de entrada
for(int i=2;i<=9;i++){ //indicamos los pines de salida
pinMode(i, OUTPUT);
}
}
void loop() {
if (digitalRead(A0)==HIGH){ //Al presionar el pulsador
saltar++; // Cambia de secuencia
if (saltar>3){ //Solo hay 4 secuencias 0,1,2 y 3 al ser 3 . .
saltar=0; // Vuelve a secuencia 0
}
while (digitalRead(A0)==HIGH){} // Mientras se pulsa no haga nada mas
}
if(saltar==0){ //Si es 1 inicie funcion de secuencia1

secuencia1();
}
if(saltar==1){ //Si es 2 inicie funcion de secuencia2
secuencia2();
}
if(saltar==2){ //Si es 3 inicie funcion de secuencia3
secuencia3();
}
if(saltar==3){ //Si es 4 inicie funcion de secuencia4
secuencia4();
}
}
void secuencia1(){
for (int i=2; i<=9; i++){ //Pin 2 al 9
digitalWrite(i, HIGH); // Prenda pin actual
digitalWrite(i-1,LOW); // Apage el Anterior
delay(50); // retardo entre prender y apagar
}
for (int i=9; i>=2; i--){ //Al contrario de la
digitalWrite(i, LOW); // anterior secuencia va de 9 a 2
digitalWrite(i-1,HIGH);
delay(50);
}
}
void secuencia2(){
int k=11; // inicializo una variable auxiliar K
for(int i=6; i<=9;i++){ //leo de 6 a 9
digitalWrite(i, HIGH); // prendo pin actual
digitalWrite(k-i, HIGH); // prendo pin de la diferencia 11-6 = 5
delay(50); //retardo
}
for(int i=9; i>=2;i--){ // Al contrario de lo anterior
digitalWrite(i, LOW);
digitalWrite(k-i, LOW);
delay(50);
}
}
void secuencia3(){
for(int i=2; i<=9; i++){
digitalWrite(i,HIGH);
delay(50);
}
for(int i=9; i>=2;i--){
digitalWrite(i,LOW);
delay(50);
}
}
void secuencia4(){
int k=11;
for(int i=2; i<=5;i++){
digitalWrite(i,HIGH);
digitalWrite(k-i,LOW);
}

delay(150);
for(int i=2; i<=5;i++){
digitalWrite(i,LOW);
digitalWrite(k-i,HIGH);
}
delay(150);
}

Primeros pasos con Arduino, prctica 1: el coche


fantstico
By salva el 19 Mayo 2010 8 Comentarios
Arduino,
Electrnica,
Proyectos
Darle 1/5
Darle 2/5
Darle 3/5
Darle 4/5
Darle 5/5
Promedio: 4.7 (7 votes)

Arduino es un sistema microcontrolado de hardware libre y cdigo abierto,


multiplataforma, barato, con un entorno de programacin sencillo y simple, basado en el
microcontrolador ATMEGA en sus diferentes versiones de Atmel. Existen diferentes
versiones de las placas arduino, yo he usado la llamada Arduino Duemilanove es la
sucesin de la Arduino Diecimila, que monta el nuevo procesador ATMega328.
Dispone de 14 pines de entada y salida digitales, de los cuales 6 se pueden usar como
salidas PWM (Pulse Width Modulation), 6 entradas analgicas, se conecta al puerto USB,
(con un cable como el de las impresoras), tambin dispone de un conector de corriente.
Todo lo que necesitamos saber sobre este estupendo sistema est en la web oficial:
http://www.arduino.cc/
En Tecnologa es un sistema ideal para controlar los proyectos que solemos realizar con
nuestros alumnos, control de puertas, barreras, semforos, ascensores,
En esta y sucesivas entregas iremos realizando prcticas bsicas basadas en este hardware:
Para comenzar necesitamos:
Descargar e instalar el entorno de programacin Arduino. No hace falta instalacin
simplemente descomprimimos el paquete en una carpeta y lanzamos el ejecutable
arduino.
Conectar nuestra placa al PC. Si no detecta automticamente los drivers stos los podremos
encontrar en la carpeta arduino-xx/drivers/FTDI USB Drivers/
Arrancamos el entorno, y en el men Tools configuramos la conexin (serial Port) y nuestra
placa (en este caso Arduino Duemilanove).

La sintaxis del lenguaje es muy parecida al lenguaje C, la estructura bsica de cualquier


programa es la siguiente:
void setup()
{
//declaro variables, asigno PinMode o inicializo las comunicaciones serie.
}
void loop()
{
//se ejecuta a continuacin, incluye el cdigo que lee entradas, activa salidas...es el ncleo
del cdigo.
}
Os aconsejo leer el manual adjunto para ampliar un poco ms en el entorno Arduino, en l
encontrareis un apartado donde se describen la base de la programacin de este sistema,
muy fcil si tenemos conocimientos de programacin.
A partir de aqu podremos empezar con nuestras prcticas:
Prctica 1: El coche fantstico.

Necesitaremos 8 diodos LED, ocho resistencias de 220 Ohmios y una placa de prototipos y
conectamos el esquema como el de la figura. Los diodos leds se encendern y apagaran
siguiendo un patrn establecido en el cdigo, se muestran tres posibles opciones, podremos
variar el tiempo de encendido y apagado, modificando la variable timer. Aqu el cdigo:
/* Coche fanttico 1*/

int pinArray[] = {2, 3, 4, 5, 6, 7,8,9};


int count = 0;
int timer = 70;
void setup(){
for (count=0;count<8;count++) {
pinMode(pinArray[count], OUTPUT);
}
}
void loop() {
for (count=0;count<8;count++) {
digitalWrite(pinArray[count], HIGH);
delay(timer);
digitalWrite(pinArray[count], LOW);
delay(timer);
}
for (count=7;count>=0;count--) {
digitalWrite(pinArray[count], HIGH);
delay(timer);
digitalWrite(pinArray[count], LOW);
delay(timer);
}
}

/* El coche fantstico2*/
int pinArray[] = {2, 3, 4, 5, 6, 7,8,9};
int count = 0;
int timer = 15;
//timer marca como queremos que vaya de rpido la rfaga de encendido-apagado de los
LEDS
void setup(){
for (count=0;count<8;count++) {
pinMode(pinArray[count], OUTPUT);
}
}

void loop() {
for (count=0;count<7;count++) {
digitalWrite(pinArray[count], HIGH);
delay(timer);
digitalWrite(pinArray[count + 1], HIGH);
delay(timer);
digitalWrite(pinArray[count], LOW);
delay(timer*2);
}
for (count=7;count>0;count--) {
digitalWrite(pinArray[count], HIGH);
delay(timer);
digitalWrite(pinArray[count - 1], HIGH);
delay(timer);
digitalWrite(pinArray[count], LOW);
delay(timer*2);
}
}

/* Estrella fugaz
*--------------* Este programa es una variante del ejemplo del coche
* fantstico. Muestra mediante un loop una estrella
* fugaz que es dibujada en una linea de LED-s
* directamente conectados a la placa Arduino
*
* Puedes controlar la velocidad a la que la estrella
* se mueve gracias a una variable llamada "waitNextLed"
*
* Tambin puedes controlar la longitud de la cola
* de la estrella a travs de la variable "tail length"
*
* @author: Cristina Hoffmann
* @hardware: Cristina Hofmann
*
*/
// Variable declaration

int pinArray [] = { 2,3,4,5,6,7,8,9,10,11,12 }; // Declaracin de los PIN-es mediante un


array
int controlLed = 13; // LED de control
int waitNextLed = 100; // Tiempo antes de encender el siguiente LED
int tailLength = 4; // Nmero de LED-s que permanecen encendidos antes de empezar a
apagarlos para formar la cola
int lineSize = 11; // Nmero de LED-s conectados (que es tambin el tamao del array)
void setup() // Configuracin de los PIN-es como salida digital
{
int i;
pinMode (controlLed, OUTPUT);
for (i=0; i< lineSize; i++)
{
pinMode(pinArray[i], OUTPUT);
}
}
void loop()
{
int i;
int tailCounter = tailLength; // Se establece la longitud de la cola en un contador
digitalWrite(controlLed, HIGH); // Se enciende el LED de control para indicar el inicio del
loop
for (i=0; i<lineSize; i++)
{
digitalWrite(pinArray[i],HIGH); // Se encienden consecutivamente los LED
delay(waitNextLed); // Esta variable de tiempo controla la velocidad a la que se mueve la
estrella
if (tailCounter == 0)
{
digitalWrite(pinArray[i-tailLength],LOW); // Se apagan los LED-s en funcin de la
longitud de la cola.
}
else
if (tailCounter > 0)
tailCounter--;
}

for (i=(lineSize-tailLength); i<lineSize; i++)


{
digitalWrite(pinArray[i],LOW); // Se apagan los LED
delay(waitNextLed); // Esta variable de tiempo controla la velocidad a la que se mueve la
estrella
}
}
- See more at: http://www.tecnosalva.com/primeros-pasos-arduino-pr
%C3%A1ctica-1-coche-fant%C3%A1stico#sthash.U4dZkTUh.dpuf

Arduino es una plataforma de electrnica abierta para la creacin de prototipos basada en


software y hardware flexibles y fciles de usar. Se cre para artistas, diseadores,
aficionados y cualquiera interesado en crear entornos u objetos interactivos.
Arduino puede tomar informacin del entorno a travs de sus pines de entrada de toda una
gama de sensores y puede afectar aquello que le rodea controlando luces, motores y otros
actuadores. El microcontrolador en la placa Arduino se programa mediante el lenguaje de
programacin Arduino (basasdo en Wiring) y el entorno de desarrollo Arduino (basado en
Processing). Los proyectos hechos con Arduino pueden ejecutarse sin necesidad de
conectar a un ordenador, si bien tienen la posibilidad de hacerlo y comunicar con diferentes
tipos de software (p.ej. Flash, Processing, MaxMSP).
Las placas pueden ser hechas a mano o compradas montadas de fbrica; el software puede
ser descargado de forma gratuita. Los ficheros de diseo de referencia (CAD) estn
disponibles bajo una licencia abierta, as pues eres libre de adaptarlos a tus necesidades.

Medidor de distancia con Arduino


y sensor HC-SR04 (II)
Aprovechando
la
entrada
anterior
donde
explicaba
el
funcionamiento de un sensor HC-SR04 he decidido modificar un
poco el cdigo para agregar unos les de
color verde y rojo. As cuando tengamos un objeto cerca se
encender el rojo y cuando lo alejemos se encender el verde.
En este caso necesitaremos un Arduino Uno Rev 3, un led de
color verde, un led de color rojo, dos resistencias de 220

ohmios. Para el que no lo sepa los colores de esta resistencia


son rojo, rojo, marrn.
Como ya coment en el post, como hacer un medidor de distancias
con Arduino y un sensor HC-SR04, hace falta que nos bajemos
la librera llamada Ultrasonic, descomprimirla y subirla a la
carpeta libreries, que se encuentra donde hayamos instalado
el Sketch de Arduino.
Descargar librera Ultrasonic

El sensor
Como ya sabemos, el sensor dispone de 4 patillas que las
conectaremos de la siguiente forma: VCC a 5V, GND a GND,
TRING y ECHO. Como vamos a usar el cdigo del post anterior
usaremos los mismos pines de Arduino que son el TRING a la 7 y
el ECHO a la 8.

El esquema
Una vez ms os dejo el esquema realizado con el
programa Fritzing, el cual es bastante visual y creo que de esta
forma se entiende mucho ms el como conectar los cables y
dems componentes electrnicos.

El cdigo
Como podis ver el cdigo es muy parecido al anterior, tan
solo tenemos que usar dos pines ms para los leds y crear un
simple if para decir que si la distancia es menos a 10cm se
encienda el led rojo y apague el verde y si es mayor que 10cm
que haga lo contrario.

C++

// Sensor de ultrasonidos HR-SC04 con leds

// David Ortega Cuadrado - dorcu.com

// 6 de Abril de 2014

// [email protected]

5
6

// Definimos los pines que vamos a usar

#define trigPin 7

#define echoPin 8

#define led 11

1
0

#define led2 10

1
1
1
2
1
3
1
4
1
5
1
6
1
7
1
8
1
9
2
0
2
1
2
2
2
3

int dis = 10; // Establecemos la distancia en cm para la comprobacion

// Librerias necesarias para el funcionamiento


#include "Ultrasonic.h"

// Declaramos el sensor ultrasonido en los pines digitales elegidos


Ultrasonic ultrasonido(trigPin,echoPin);

void setup() {
Serial.begin (9600);
pinMode(trigPin, OUTPUT); // Establecemos el pin trig como salida
pinMode(echoPin, INPUT); // Establecemos el pin echo como entrada
pinMode(led, OUTPUT); // Establecemos el led verde como salida
pinMode(led2, OUTPUT); // Establecemos el rojo verde como salida
}

void loop() {
int distancia;

distancia = ultrasonido.Ranging(CM);

2
4
2
5
2

if (distancia < dis){


digitalWrite(led,LOW); // Apagamos el led verde
digitalWrite(led2,HIGH); // Encendemos el led rojo

Serial.print("Led rojo - Distancia: ");

2
7

Serial.print(ultrasonido.Ranging(CM));

2
8

Serial.println(" cm");
} else {
digitalWrite(led,HIGH); // Encendemos el led verde

2
9

digitalWrite(led2,LOW); // Apagamos el led rojo

3
0

Serial.print("Led verde - Distancia: ");


Serial.print(ultrasonido.Ranging(CM));

3
1
3
2
3
3
3
4
3
5
3
6
3
7
3
8
3
9
4
0
4
1
4
2
4
3
4
4

Serial.println(" cm");
}

delay(500);
}

4
5
4
6
4
7
4
8

Descargar cdigo desde Github


Ya sabis que si tenis alguna duda o queris comentar lo que
queris respecto al cdigo o al esquema lo podis hacer
mediante los comentarios de abajo.

You might also like