Sei sulla pagina 1di 47

Arduino:

What is Arduino?
Arduino es un microcontrolador de una sola
tarjeta de tipo “open source”. Está diseñado
de tal forma que sean más accesibles los
proyectos de electrónica multidiciplinarios.

La idea comenzó en Italia,


y su propósito inicial era
hacer los proyectos de los
estudiantes más
accesibles comparado con
otros sistemas
Generalidades

 El Arduino Uno es una placa electrónica


basada en el microprocesador Atmega328.
cuenta con lo siguiente:
 14 pines digitales de entrada / salida, de las
cuales 6 se puede utilizar como salidas
PWM,
 6 entradas analógicas,
 Un cristal de 16 MHz.
 una conexión USB,
 un conector de alimentación,
 ICSP - In-circuit serial programming
 un botón de reinicio.
 Contiene todo lo necesario para utilizar
microcontrolador, basta con conectarlo a una
computadora con un cable USB o a un
adaptador AC-DC o batería para empezar.
Especificaciones
Summary
Microcontroller ATmega328
Operating Voltage 5V
Input Voltage (recommended) 7-12V
Input Voltage (limits) 6-20V
Digital I/O Pins 14 (of which 6 provide PWM output)
Analog Input Pins 6
DC Current per I/O Pin 40 mA
DC Current for 3.3V Pin 50 mA
32 KB (ATmega328) of which 0.5 KB
Flash Memory
used by bootloader
SRAM 2 KB (ATmega328)
EEPROM 1 KB (ATmega328)
Clock Speed 16 MHz
Generalidades

 Hay tres tipos de memoria en la placa de


arduino:
 La memoria flash, es donde se almacena el
programa o SKETCH.
 SRAM es donde se crean y manipulan las
variables cuando el programa se ejecuta.
 EEPROM es el espacio de memoria que los
programadores pueden utilizar para
almacenar información a largo plazo.
Entradas / Salidas digitales

 Entrada y salida

Cada uno de los 14 pines digitales, se puede


utilizar como una entrada o salida, utilizando
funciones digitalRead () pinMode (),
digitalWrite ()
Entradas / Salidas digitales

 Estas entradas y salidas funcionan a 5


voltios.
 Cada pin puede proporcionar o recibir un
máximo de 40 mA y tiene una resistencia
pull-up interna (desconectada por defecto) de
20 a 50 kOhm.
Entradas / Salidas digitales

 Además, algunos pines tienen funciones


especializadas:

1.- Serie: 0 (RX) y 1 (TX). Se utiliza para


recibir (RX) y de transmisión (TX) de datos
en serie TTL.
Entradas / Salidas digitales

 Interrupciones externas: 2 y 3. Estos pines


pueden ser configurados para activar una
interrupción en un valor bajo, un flanco
ascendente o descendente, o un cambio en
el valor. Esto se logra a través de la función
attachInterrupt ()
Entradas / Salidas digitales

 PWM: 3, 5, 6, 9, 10, y 11. Proporcionar salida


PWM de 8 bits con la función analogWrite ().
 LED: 13. Hay un LED permanentemente
conectado al pin digital 13. Cuando el pin
está en un valor alto, el LED se enciende, y
en nivel bajo, se apaga.


Salidas analógicas

 Contiene 6 entradas analógicas,


etiquetados A0 a A5, cada uno de los cuales
proporcionan 10 bits de resolución (es decir,
1,024 valores diferentes). Por defecto se
miden desde cero a 5 voltios, aunque es
posible cambiar el extremo superior de su
rango.

Comunicación

 El Arduino Uno tiene un número de


facilidades para la comunicación con una
computadora, con otro Arduino o con otros
microcontroladores.
Comunicaciones

 UART TTL serie, que está disponible en los


pines digitales 0 (RX) y 1 (TX).
 UART = Universal Asynchronous
Receiver-Transmitter
Comunicaciones

 El software de Arduino incluye un monitor de


puerto serie que permite enviar texto simple
hacia y desde la placa Arduino.
 Los LEDs RX y TX de la placa parpadearán
cuando los datos se transmiten a través del
chip USB a serie y la conexión USB a la
computadora
Comunicaciones

 El ATmega328 también soporta la


comunicación I2C, que le permite conectarse
con una gran cantidad de periféricos que
soportan este protocolo.
Arduino Software
La plataforma de
programación fue
diseñada en JAVA para
ayudar a los usuarios a
familiarizarse con la
programación. El
lenguaje utilizado para
escribir código es C/C++
utilizando solamente
DOS funciones para
escribir un programa.
Las rutinas del programa
Cada programa en Arduino es llamado un
SKETCH y tiene dos funciones requeridas,
llamadas RUTINAS

void setup ( ) { } - Todo el código dentro de las llaves se


ejecutará solamente una vez, inmediatamente después de iniciado el
programa.

void loop ( ) { } - Esta función corre después de setup Todo el


código dentro de las llaves correrá una y otra vez hasta que se retire la
energía.
Sntaxis

// - Comentario simple
/* */ - Comentario múltiple
{ } – Usado para marcar el inicio y el final de un segmento de código
; - usado para finalizar una línea de código
Programming - Variables

Int (integer) – Almacena un número de dos bytes. (16 bits), no tiene punto
decimal. El valor debe estar entre -32,768 y 32,768.

long – Se utiliza cuando int no es lo suficientemente grande. Este toma 4


bytes (32 bits) de RAM y tiene un rango de -2147483648 y 2147483648.

boolean – Una variable que puede tomar los valores “true” o “false”. Es
útil, ya que sólo ocupa 1 bit de RAM.

float – Se utiliza para numeros con punto decimal. Se necesita 4 bytes de


RAM y tiene un alcance de -3.4028235E38 3.4028235E38

Char (character) – Almacena un carácter con el código ASCII ("A" = 65).


Usa 1 byte de RAM
Operadores Matemáticos
Se utilizan para manipular números

= (Asignación) hace que una variable sea igual a otra


variable o a una expresión. Por ejemplo, x = 10 * 2, con lo cual x
toma el valor de 20.
% (módulo) – esto da el residuo cuando se divide un número
por otro. Por ejemplo 12 % 10 da 2.
+ (suma)
- (resta)
* (multiplicación)
/ (división)
Operadores de Comparación
Utilizados para hacer comparaciones lógicas

== (igual a) – por ejemplo 12==10 es FALSE and 12 ==12


es TRUE.

!= (no igual)
< (menor que)
> (mayor que)
<= Menor o igual
>= mayor o igual
Primer Programa
 /*
 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
 }
Segundo programa

 Conexión de dos LEDS que se encienden en


forma alternada.
 int rojo=12,verde=11;

 void setup() {
 pinMode(rojo, OUTPUT);
 pinMode( verde,OUTPUT);
 }
 void loop() {
 digitalWrite(rojo, HIGH);
 digitalWrite(verde, LOW);
 delay(1000);
 digitalWrite(rojo, LOW);
 digitalWrite(verde, HIGH);
 delay(1000);
 }
 int rojo=12,verde=11;
 void setup() {
 pinMode(rojo, OUTPUT);
 pinMode( verde,OUTPUT);
 }
 void loop() {
 digitalWrite(rojo, HIGH);
 digitalWrite(verde, LOW);
 delay(1000);
 digitalWrite(rojo, LOW);
 digitalWrite(verde, HIGH);
 delay(1000);
 }
Programming – Control Structures
These execute code based on CONDITIONS.
Here are just a few.
if(condition) { }
else if (condition) { }
else(condition) { }

This will execute the code between the curly braces if the
condition is true, and if not test the condition of the “else if”. If that
is false , the “else” code will execute.

for (int i =0; i < #repeats; i ++) { }


Used when you would like to repeat a line of code a specific # of times.
Often called a FOR LOOP.
Programming - Digital

pinmode (pin, mode) ; - Used to address the pin # on


the Arduino board you would like to use 0-19. The mode
can either be INPUT or OUTPUT.

digitalwrite (pin, value); - Once a pin is set to output


it can be set to either HIGH (5 Volts) or LOW(0 volts).
This basically means turn ON and OFF.

Note: There are ways to use the board as analog. Those will be explained later.
Let’s Begin – Learning Goals
Learning Goals: The student will be able to:
1. Build a complete circuit using the Arduino microprocessor
2. Identify important electrical components in a circuit and explain their
use
3. Identify and apply specific elements in “C” code used to run a
program in conjunction with how a circuit is built
Scales of Measurement – Do you get it?
Lesson #1 – Blinking LED
What will you need? Arduino, breadboard, 4
wires, 10mm LED(large white), 560W resistor,
USB cable.

Longer Lead is POSITIVE


LEDs
An LED (light emitting diode) emits light when a
small current passes through it. You can
identify it as it looks like a small bulb

It only works in ONE


direction. So make sure you
attach it correctly. Also it
often needs a resistor to
limit the current going to it.

Schematic symbol
Resistors
Resistors restrict the amount of electrical
current that can flow through a circuit. The
color bands indicate the VALUE of the
resistor
Note: it is easy to grab the
WRONG one so be careful.
Also, it does not matter which
way the resistor is wired.

Schematic symbol
The schematic This is basically a SERIES circuit
where the resistor and LED are wired
one after another.

1. Run a red wire from the 5V on the


Arduino to the red strip on the BB.
2. Run a black wire from the
GROUND(GND) on the Arduino to
the blue strip on the BB.
3. Place the LED on H 22 and 21 with
the longer lead(+) of the LED in
H22.
4. Place a resistor on I21 and I11.
Notice that both the resistor and
LED share row 21.
5. Run a red wire from Digital 13 port
on Arduino to F22
6. Run a black wire from J11 to the
blue strip.
Writing the code - Integers
Load up the Arduino software.

Begin by using the variable “int” or integer and


let’s tell the Arduino which port the LED is in.
Writing the code - Setup

Remember that SETUP is used for things that only need


to be done once. Therefore we must tell the Arduino that
the LED in port 13 is an output. That means when we
input data it outputs an outcome or result.
Writing the code - Loop

The next steps is telling the Arduino what we want to do


with the LED. We first need to use the digitalWrite
command to turn the LED ON. We then use the “delay”
command to specify and amount of time in milliseconds.
We then use the same command to turn it OFF then wait
again. Since this is a loop the process will repeat forever
until the power is removed.
Compile
To compile your
sketch, click the
checkmark.

Make sure your


Arduino is plugged
into an available USB
port.

Click the arrow to


download the
program to Arduino. If
everything is attached
correctly. The LED
should blink.
Your turn
Using what you have learned. Create a new
program and record the program on the
lesson sheet. Do NOT use more than 1 LED
and DO NOT remove the resistor. Leave the
circuit as is.

Once you have created your own program,


follow the directions on the next slide.
Controlling the Brightness
Switch the LED pin to #9 (change the integer in
the code as well) and then replace with this
line in the loop

analogwrite(ledPin,new number)

Where the “new number” can be any value


between 0 and 255. Write and show your
new sketch on the project sheet. Compile,
download, and test.
Fading

Go to FILE, then EXAMPLES, then ANALOG,


then FADING.

Follow the hyperlink which explain how to


FADE. Create a program that uses this idea
and record on project sheet. Be sure to
explain which C-code element allows this
idea to work.

Potrebbero piacerti anche