2
IMPORTANTE
3
CMO EMPEZAR CON ARDUINO
Este manual le ayudar a entender lo que es y cmo funciona Arduino para
comenzar a construir sus propios proyectos electrnicos.
Qu es Arduino?
Arduino es una plataforma de electrnica abierta para la creacin de prototipos
basada en software y hardware flexibles y fciles de usar.
Tiene todo lo que necesita para uso bsico soldado en una pequea placa de
circuito. La placa contiene el microcontrolador y ofrece un cmodo acceso a las
entradas y salidas. Las entradas son dispositivos como sensores (sensores de
luz, termmetros, giroscopios, etc.) y elementos de interfaz humana (botones,
interruptores, perillas). Las salidas son todos los elementos electrnicos que
quiera ser capaz de controlar, tales como luces, pantallas, motores y servos. Un
microcontrolador tiene todas las partes bsicas de un ordenador (procesador,
memoria, pines de entrada/salida) en un solo chip y ejecuta el software que
se carga sobre ella desde una computadora, lo que le permite manipular los
resultados basados en datos que recibe de las entradas.
Arduino es open source. Como hardware de cdigo abierto, los esquemas para
Arduino estn disponibles para cualquier persona gratuitamente, por si quiere
comprar los componentes electrnicos y una placa y construir su propio Arduino.
Existe una enorme gama de proyectos que necesitan un microcontrolador. Un
proyecto simple podra ser algo como una tira de luz LED. Un circuito bsico
puede encender las luces LED, pero con el fin de conseguir que cambie de color
y ejecutar patrones necesita un microcontrolador. Proyectos ms complejos
podran ser un brazo robtico, una exhibicin de LED hologrfico o una caja de
arena de gato auto limpiable.
4
Deber descargar un hardware adicional para programar el circuito. Necesitar
un cable USB para programarlo y si quiere ser capaz de ejecutar su proyecto
cuando no est cerca de la computadora, necesitar un adaptador de corriente
AC-DC o batera y cable. Usted encontrar estos componentes en Steren.
Escudos
Un escudo es una placa de circuito adicional a su Arduino. Generalmente, un
escudo se coloca encima de la placa base Arduino, se conecta con sus pines
I/O y permite al Arduino especializarse aadiendo capacidades adicionales, o
proporcionando una interfaz ms conveniente para su proyecto. Por ejemplo,
un escudo podra permitir integrar un chip GPS o una tarjeta SD a su proyecto.
Algunos escudos se pueden apilar uno encima del otro, para agregar varias
funciones adicionales.
PROGRAMACIN ARDUINO
1. Descargue el entorno de desarrollo de Arduino (www.arduino.cc) e instlelo
en su PC. El ambiente est disponible para Windows, Mac y Linux e incluye todo
lo que necesita para empezar a programar.
2. Conecte el Arduino a la computadora y si est usando una mquina Windows,
espere a que se instale el controlador.
3. Cuando comience a usar el editor de Arduino, deber configurar en el men
Herramientas, en la parte superior del editor, la opcin de tarjeta y la opcin de
Puerto Serial; en la primera seleccione el modelo de Arduino que compr. En la
segunda elija el puerto al que est conectado el Arduino. Si tiene dudas acerca
de este puerto, simplemente desconecte el Arduino y la opcin que desaparezca
es su puerto.
5
Finalmente, estar listo para escribir programas (el editor de Arduino se refiere
a ellos como sketches) para su proyecto. Necesitar cierta familiaridad con
programacin en C++, variables, funciones, declaraciones if y bucles, pero los
sketches Arduino suelen ser ms simples.
SKETCHES
La mejor manera de aprender programacin de Arduino es a travs de los
sketches de ejemplo incluidos en el IDE de Arduino. stos se encuentran en el
men Archivo>Ejemplos y puede encontrar muchos ejemplos en Internet.
Una vez que ha escrito un sketch, simplemente haga clic en el botn Cargar
y ste ser enviado a su placa Arduino. El microcontrolador se reiniciar y
ejecutar su sketch hasta subir uno diferente.
A continuacin se muestran pequeos proyectos paso a paso.
1. Intermitente
6
SCL
SDA
AREF
GND
13
IOREF A11 12
RESET 11
3V3 A10
10
5V A9
A8 9
GND
POWER
8
GND
V1n
7
A7 6
A0 5
A6
A1 4
DIGIRAL (PWM)
A2 3
A3 2
A4 TX1 11
ANALOG IN
A5 AX1 00
SCL
SDA
AREF
GND
13
IOREF A11 12
RESET 11
3V3 A10
10
5V A9
A8 9
GND
POWER
8
GND
V1n
7
A7 6
A0 5
A6
A1 4
DIGIRAL (PWM)
A2 3
A3 2
A4 TX1 11
ANALOG IN
A5 AX1 00
7
Programa
/*
* Intermitente
*
* Ejemplo bsico con Arduino. Encendido y apagado de un LED
* con una cadencia de 1 s usando el PIN 13 como salida
* no es necesario usar una resistencia para el LED
* la salida 13 de Arduino la lleva incorporada.
*
* http://www.arduino.cc/en/Tutorial/Blink
*/
int ledPin = 13; // Definicin de la salida en el PIN 13
void setup() //Configuracin
{
pinMode(ledPin, OUTPUT); // designa la salida digital al PIN 13
}
void loop() // bucle de funcionamiento
{
digitalWrite(ledPin, HIGH); // activa el LED
delay(1000); // espera 1 s (tiempo encendido)
digitalWrite(ledPin, LOW); // desactiva el LED
delay(1000); // espera 1 s (tiempo apagado)
}
8
2. Alarma
10 K
9
Programa
10
3. Secuencia Bsica de 3 LEDs
GND 8 7
6
11
Programa
12
4. Contador
Se trata de contar las veces que se pulsa un botn conectado en la entrada 7
de Arduino al mismo tiempo que cada vez que contamos encendemos el LED
conectado en la salida 13. El valor de la variable que almacena el nmero de
impulsos generados se enva a la PC para que se visualice en la pantalla.
10 K
13
Programa Contador
/* Detecta si el botn conectado a la entrada 7 ha sido presionado y enciende
el LED
* Enva al PC el valor de la variable de cuenta Contador va puerto serie.
*
* Christian Nold & Erica Calogero
*
*/
int LED = 13;
int Boton = 7;
int valor = 0;
int contador = 0;
int estadoanteriorboton = 0;
void setup()
{
Serial.begin(9600); // Configura velocidad de transmisin a 9600
pinMode(LED, OUTPUT); // inicializa como salida digital el pin 13
pinMode(Boton, INPUT); // inicializa como entrada digital el 7
digitalWrite(Boton,HIGH); // Habilitamos la resitencia interna Pull-up del PIN7
}
void loop()
{
valor = digitalRead(Boton); // lee el valor de la entrada digital pin 7
digitalWrite(LED, !valor); // Escribimos en la salida el valor ledo negado
if(valor != estadoanteriorboton){
if(valor == 1){
14
contador++;
Serial.print(contador);
Serial.write(10);
Serial.write(13);
}}
estadoanteriorboton = valor;
}
Podramos prescindir de la resistencia colocada con el pulsador si se habilita la
resistencia interna Pull-up de la entrada PIN7, en ese caso el circuito quedara
como el siguiente:
15
El programa en este caso sera muy parecido al anterior. Obsrvese que ahora
al pulsar el botn introducimos un = en el PIN7, por lo tanto, si quiero que se
encienda la salida PIN13 debo escribir en ella el valor ledo del pulsador negado,
es decir !valor.
16
{
valor = digitalRead(Boton); // lee el valor de la entrada digital pin 7
digitalWrite(LED, !valor); // Escribimos en la salida el valor ledo negado
if(valor != estadoanteriorboton){
if(valor == 1){
contador++;
Serial.print(contador);
Serial.write(10);
Serial.write(13);
}}
estadoanteriorboton = valor;
}
5. Entrada Analgica
17
Programa
/* Entrada Analgica */
int potPin = 5; // selecciona el pin de entrada para colocar el potencimetro
int val = 0; // variable para almacenar el valor ledo por la entrada analgica
void setup() {
Serial.begin(9600);
}
void loop() {
val = analogRead(potPin); // lee el valor del canal de ENTRADA analgica
Serial.print(val); // Enva al PC el valor analgico ledo y lo muestra en pantalla
Serial.write(10);
delay(100);
}
18
Tenga en cuenta que el motor debe ser de bajo consumo por dos motivos:
primero porque si alimentamos en las pruebas desde el conector USB no
debemos sacar demasiada corriente de la computadora y segundo, porque el
transistor es de una corriente limitada.
El diodo 1N4001 se coloca como proteccin para evitar que las corrientes
inversas creadas en el bobinado del motor puedan daar el transistor.
19
La tensin que sacaremos a la salida 10 (analgica tipo PWM) variar en forma
de rampa ascendente y descendente de manera cclica, tal como vemos en la
figura. Este efecto lo conseguimos con una estructura del tipo for:
20
Programa
int valor = 0; // variable que contiene el valor a sacar por el terminal analgico
int motor = 10; // motor conectado al PIN 10
void setup() { } // No es necesario
void loop() {
for(valor = 0 ; valor <= 255; valor +=5) {
// se genera una rampa de subida de tensin de 0 a 255, es decir, de 0 a 5v
analogWrite(motor, valor);
delay(30); // espera 30 ms para que el efecto sea visible
}
for(valor = 255; valor >=0; valor -=5) {
// se genera una rampa de bajada de tensin de 255 a 0, es decir, de 5 a 0v
analogWrite(motor, valor);
delay(30);
}
}
21
Programa
int valor = 0; // variable que contiene el valor a sacar por el terminal analgico
int motor = 10; // motor conectado al PIN 10
int potenciometro=0; // Se define la entrada analgica
void setup() { } // No es necesario
void loop() {
valor = analogRead(potenciometro); // se lee el valor de la entrada analgica
y se asigna a val
analogWrite(motor, valor); // Se manda a la salida analgica 0 el valor ledo
delay(30); // espera 30 ms para que el efecto sea visible
}
Esquema
22
7. Control de un motor de cc con el driver L293D
Voltaje efectivo
Tiempo
23
Cuando el tiempo que el pulso est activo es la mitad del periodo de la seal
o el parmetro duty cycle est al 50%, el voltaje efectivo es la mitad del voltaje
total de entrada.
Voltaje
Voltaje efectivo
Tiempo
Cuando el tiempo que el pulso est activo es la mitad del periodo de la seal
o el parmetro duty cycle est al 50%, el voltaje efectivo es la mitad del voltaje
total de entrada.
Cuando el duty cycle es reducido al 25%, el voltaje efectivo es un cuarto del
voltaje total de entrada. Entonces la velocidad del motor disminuye.
De esta forma, controlando el duty cycle o el tiempo que el pulso est activo
(frecuencia), podemos controlar la velocidad del motor de continua.
Una forma de realizar dicho control en Arduino es utilizando la salida analgica
PWM.
Hay que recordar que la seal de salida PWM (pines 9, 10) es una seal de
frecuencia constante (30769 Hz) y que slo nos permite cambiar el duty cycle
o el tiempo que el pulso est activo (on) o inactivo (off) utilizando la funcin
analogWrite().
24
La otra forma es generando seales PWM utilizando la capacidad del
microprocesador a travs de la funcin digitalWrite().
Si queremos controlar simultneamente la velocidad y direccin de un motor,
necesitamos utilizar un circuito integrado o chip, llamado de forma general
puentes H, por ejemplo como el L293D.
Chip L293D/B (puente H):
Es un circuito integrado o chip que puede ser utilizado para controlar
simultneamente la velocidad y direccin de dos motores de continua (contiene
dos puentes H). La diferencia entre el modelo L393D y L293B es que el primero
viene con diodos de proteccin que evitan los daos generados por los picos de
voltaje que puede producir el motor.
Al puerto
paralelo:
pines
1y2
Contiene 4 pines digitales (2, 7, 10, 15) para controlar la direccin de los motores.
25
Los pines enable (1, 9) admiten como entrada una seal PWM y se utiliza para
controlar la velocidad de los motores con la tcnica de modulacin de ancho de
pulso.
Los motores van conectados entre uno de los pines 3, 6, 11, o 14. La tensin Vss
es la que alimentar o dar potencia al motor.
Programa
26
Esquema
22
TXD314
RXD315
TXD216
RXD217
TXD118
RXD217
SDA 20
SCL 21
7
6
5
4
3
2
1
0
AREF
GND
13
12
11
10
9
8
PWM 24
COMMUNICATION 26
28
30
32
34
36
DIGITAL
38
40
42
44
46
48
50
52
POWER
IOREF
RESET
ANALOG IN
3V3
10
11
12
5V GND VIN
13
14
15
0
1
2
3
4
5
6
7
8
9
27
Programa
// Control de Motor con driver L293D
int valor = 0; // variable que contiene el valor
int motorAvance = 10; // Avance motor --> PIN 10
int motorRetroceso = 11; // Retroceso motor --> PIN 11
void setup() { } // No es necesario
void loop() {
analogWrite(motorRetroceso, 0); // Motor hacia delante ... sube la velocidad
for(valor = 0 ; valor <= 255; valor+=5) {
analogWrite(motorAvance, valor);
delay(30);
}
for(valor = 255; valor >=0; valor-=5) { // Motor hacia delante ... baja la
velocidad
analogWrite(motorAvance, valor);
delay(30);
}
analogWrite(motorAvance, 0); // Motor hacia detrs ... sube la velocidad
for(valor = 0 ; valor <= 255; valor+=5) {
analogWrite(motorRetroceso, valor);
delay(30);
}
for(valor = 255; valor >=0; valor-=5) { // Motor hacia detrs ... baja la velocidad
analogWrite(motorRetroceso, valor);
delay(30);
}
}
28
9. Utilizar un relevador para encender dispositivos de 120 V
Este ejemplo ensea cmo encender una bombilla de 120 V de corriente alterna
(AC) mediante un circuito de 5 V de corriente continua (DC) gobernado por
Arduino. Se puede utilizar con cualquier otro circuito de 120 V con un mximo
de 10 A (con el rel del ejemplo).
Qu es un relevador?
El relevador o rel es un dispositivo electromecnico que funciona como un
interruptor controlado por un circuito elctrico en el que, por medio de un
electroimn, se acciona un juego de uno o varios contactos que permiten abrir o
cerrar otros circuitos elctricos independientes.
De aqu extraemos una informacin muy importante: Podemos separar dos
circuitos de forma que funcionen con voltajes diferentes.
Uno a 5 V (Arduino) y otro a 120 V
(la bombilla).
Como se ve en el esquema inferior,
hay dos circuitos. El del cableado
NEGRO funciona a 5 V de DC y el
del cableado ROJO a 120 V de AC.
22
TXD314
RXD315
TXD216
RXD217
TXD118
RXD217
SDA 20
SCL 21
7
6
5
4
3
2
1
0
AREF
GND
13
12
11
10
9
8
PWM 24
COMMUNICATION 26
28
30
32
34
36
DIGITAL
38
40
42
44
46
48
50
52
110 V
POWER
IOREF
RESET
ANALOG IN
3V3
10
11
12
5V GND VIN
13
14
15
0
1
2
3
4
5
6
7
8
9
29
Programa
/*
Enciende y apaga una bombilla de 220 V, cada 2 segundos, mediante
un rel conectado al PIN 8 de Arduino
*/
int relayPin = 8; // PIN al que va conectado el rel
void setup(){
pinMode(relayPin, OUTPUT);
}
void loop() {
digitalWrite(relayPin, HIGH); // ENCENDIDO
delay(2000);
digitalWrite(relayPin, LOW); // APAGADO
delay(2000);
}
30
ESPECIFICACIONES
Micro controlador: MEGA32U4
Alimentacin: 5-12 V - - -
Frecuencia de operacin: 16 MHz
Puertos de entrada anloga: 12
Puertos de entrada/salida digital: 20 (incluyendo puertos PWM)
Capacidad de memoria flash: 32 kB
SRAM: 2,5 kB
EEPROM: 1 kB
Boot loader: Leonardo
Salida PWM: S
Salida de voltaje: 5 V - - -
Switch reset: S
Comunicacin a la PC: USB
Software empleado: Arduino
CONDICIONES
1.- Para hacer efectiva la garanta, presente esta pliza y el producto, en donde fue adquirido o en
Electrnica Steren S.A. de C.V.
2.- Electrnica Steren S.A de C.V. se compromete a reparar el producto en caso de estar defectuoso sin
ningn cargo al consumidor. Los gastos de transportacin sern cubiertos por el proveedor.
3.- El tiempo de reparacin en ningn caso ser mayor a 30 das, contados a partir de la recepcin del
producto en cualquiera de los sitios donde pueda hacerse efectiva la garanta.
4.- El lugar donde puede adquirir partes, componentes, consumibles y accesorios, as como hacer vlida esta
garanta es en cualquiera de las direcciones mencionadas posteriormente.
This manual includes all the feature operations and troubleshooting necessary
to install and operate your new Sterens PCB compatible with Arduino
Leonardo.
www.steren.com
The instructions of this manual are for reference about the product. There may
be differences due to updates.
Please check our website (www.steren.com) to obtain the latest version of the
instruction manual.
2
IMPORTANT
HIGHLIGHTS
The PCB with MEGA32U4 Atmel micro controller allows you to use all input and
output ports, helping to students and hobbyists not to worry about control stage.
The communication and programming interface is performed using free
software (used by Arduino) and cab be connected to the PC through the USB
port. It has an ISCP port.
3
GETTING STARTED WITH ARDUINO
This manual will help you understand what it is and how Arduino works to begin
to build your own electronic projects.
What is Arduino?
Arduino is an electronic open platform for prototype creation based on flexible
and easy to use software and hardware.
It has everything you need for basic use soldered on a small circuit. The
plate contains the microcontroller and provides convenient access to inputs
and outputs. Entries are devices such as sensors (sensors, thermometers,
gyroscopes, etc.) and elements of human interface (buttons, switches and
knobs). The outputs are electronic components that you want to be able to
control, such as lights, displays, motors and servos. A microcontroller has all the
basic parts of a computer (processor, memory, input/output pins) on a single chip
and runs the software that is loaded on it from a computer, which allows you to
manipulate the results based on data it receives at the inputs.
Arduino is open source. As open source hardware, schemes for Arduino are
available to anyone for free, if you want to buy electronic components and a plate
and build your own Arduino.
There is a huge range of projects that need a microcontroller. A simple project
could be something like a LED light strip. A basic circuit can turn the LED lights
on, but in order to get to change color and patterns you will need a microcontroller.
More complex projects might be a robotic arm, a holographic LED display or
cleanable auto cat litter box.
4
You need to download an additional hardware to set the circuit. You will need
a USB cable for programming it and if you want to be able to run your project
when you are not near your computer, you will need an adapter current AC-DC or
battery and cable. You will find these components on Steren.
Shields
A shield is an additional circuit to your Arduino board. Usually, a shield is placed
over the base Arduino, connects with its I/O pins and allows the Arduino specialize
by adding additional capabilities, or providing a more convenient interface for
your project. For example, a shield could allow to integrate a GPS chip or an SD
card to your project. Some shields can be stacked one on top of the other, to add
several additional functions.
ARDUINO PROGRAMMING
1. Download the Arduino development environment and install it on your PC. The
environment is available for Windows, Mac and Linux and includes everything
you need to begin programming.
2. Connect the Arduino to the computer and (if you are using a Windows machine)
wait for the drivers to be installed.
3. When you start using the Arduino editor, you need to configure in the Tools
menu at the top of the editor, the card and serial port options; in the first, select
the bought Arduino model. In the second select the port at which the Arduino
is connected to. If you have questions about this port, simply disconnect the
Arduino and the option that disappears is your port.
5
Finally, you are ready to write programs (the Arduino editor refers to them as
sketches) for your project. Youll need some familiarity with C++programming,
variables, functions, if statements and loops, but the Arduino sketches tend to
be simpler.
SKETCHES
The best way to learn programming Arduino is through the example sketches
included in the Arduino IDE. These are located in the file menu > examples and
many examples can be found on the Internet.
Once you have written a sketch, simply click the load button and it will be sent
to your Arduino board. The microcontroller will restart and run your sketch until
it gets a different one.
Below you will find small step by step projects.
1. Flashing
It is a basic exercise that shows how to turn a LED that is connected to PIN 13 of
Arduino configured as output. Turn on and off time is 1 second.
Plot and scheme
Since Arduino PIN 13 has an internal resistance, the red LED is placed without
resistance in series; if you place the led in another output you should place
a resistance of between 220 and 500 ohms, depending on the power LED
consumption.
6
SCL
SDA
to 10 PIN output.
AREF
GND
13
IOREF A11 12
RESET 11
3V3 A10
10
5V A9
A8 9
GND
POWER
8
GND
V1n
7
A7 6
A0 5
A6
A1 4
DIGIRAL (PWM)
A2 3
A3 2
A4 TX1 11
ANALOG IN
A5 AX1 00
POWER
8
GND
V1n
7
A7 6
A0 5
A6
A1 4
DIGIRAL (PWM)
A2 3
A3 2
A4 TX1 11
ANALOG IN
A5 AX1 00
7
Program
/*
* Intermittent
*
* Basic example with Arduino. Switching on and off of a LED
* with a cadence of 1 s using the 13 PIN as output
* is not necessary to use a resistor for LED
* exit 13 Arduino has it built-in.
*
* http://www.arduino.cc/en/Tutorial/Blink
*/
int ledPin = 13; // Definition of the PIN 13 output
void setup() //Configuration
{
pinMode(ledPin, OUTPUT); // designates the PIN 13 digital output
}
void loop() // operating loop
{
digitalWrite(ledPin, HIGH); // activates the LED
delay (1000); // 1 s wait (on-time)
digitalWrite(ledPin, LOW); // disables the LED
delay (1000); // 1 s wait (off-time)
}
8
2. Alarm
When you press the button (input 5 to 0), output 13 turns on and shuts off
intermittently.
How it works:
When the I5 = 1 then O13 = 0
When the I5 = 0 then O13 = 0-1 (intermittent 200,200 ms)
10 K
9
Program
10
3. Basic 3 LEDs sequence
It turns on and off 3 LEDs placed in the 6, 7 and 8 outputs (PIN 6 PIN 7 and PIN
8) with a cadence of 200 ms. Assigned to each LED are ledPin1, ledPin2 and
ledPin3 variables.
GND 8 7
6
11
Program
12
4. Counter
It counts the times a button connected to Arduino input 7 is pressed whenever
we have we light the LED connected at output 13. The value of the variable that
stores the number of pulses generated is sent to the PC so that it is displayed
on the screen.
10 K
13
Program counter
/ * Detects if connected to the input jack 7 button has been pressed and LED
lights up
* Send the value of the variable Counter account via serial port to the PC.
*
*
*/
int LED = 13;
int Button = 7;
int value = 0;
int counter = 0;
int buttonlaststate = 0;
void setup()
{
Serial.begin(9600); // Configures transmission speed to 9600
pinMode(LED, OUTPUT); // Initializes as a digital output pin 13
pinMode(Boton, INPUT); // initializes as a digital input the 7
digitalWrite(Boton,HIGH); // Enable internal resistance Pull-up from PIN7
}
void loop()
{
value = digitalRead(Boton); // Reads the digital input pin 7 value
digitalWrite(LED, !valor); // Write in the output the read denied value
if(value != int buttonlaststate){
if(value == 1){
counter++;
14
Serial.print(counter);
Serial.write(10);
Serial.write(13);
}}
int buttonlaststate = value;
}
We could avoid the resistance placed at the button if the internal resistance of
PIN7 is enabled, in this case the circuit would be as follows:
15
The program in this case would be very similar to the previous. Note that now
when the button is pressed we introduce an = at PIN7, therefore, if you want
to start the PIN13 output, you should write in it the value read from the denied
button, i.e. !value.
/ * Detects if connected to the input jack 7 button has been pressed and LED
lights up
* Send the value of the variable Counter account via serial port to the PC.
*
*
*/
int LED = 13;
int Button = 7;
int value = 0;
int counter = 0;
int buttonlaststate = 0;
void setup()
{
Serial.begin(9600); // Configures transmission speed to 9600
pinMode(LED, OUTPUT); // Initializes as a digital output pin 13
pinMode(Boton, INPUT); // Initializes as a digital input the 7
digitalWrite(Button,HIGH); // Enable internal resistance Pull-up from PIN7
}
void loop()
{
16
valor = digitalRead(Button); // Reads the digital input pin 7 value
digitalWrite(LED, !value); // (Write in the output the read denied value
if(value != int buttonlaststate){
if(value == 1){
counter++;
Serial.print(counter);
Serial.write(10);
Serial.write(13);
}}
int buttonlaststate = value;
}
5. Analog input
17
Program
/ * Analog input * /
int potPin = 5; // Selects the input PIN to put the potentiometer
int val = 0; // variable to store the value read from the analog input
void setup() {
Serial.begin(9600);
}
void loop() {
val = analogRead(potPin); // Reads the value from the input analog channel
Serial.print(val); // Sends to the PC the read analog value and displays it
on screen
Serial.write(10);
delay(100);
}
With this example we are going to control the speed of a DC motor using a
BD137 transistor. Uses the possibility of sending a PWM signal to one of the
outputs set up as analog.
18
Please note that the motor must be low power for two reasons: first because
if we feed testing from USB connector must not pull too much current from the
computer and second, because the transistor is current limited.
19
Analog-value
The tension that we are going to pull from outputt 10 (analog type PWM) will
vary on way to ramp up and down cyclically. We get this effect with a structure
for type:
Note that increases in the voltage value range from 5 at 5 and we have to
consider that 0v equals 0 and 5v is equivalent to 255.
20
Program
int value = 0; // a variable that contains the value to get analog input terminal
int motor = 10; // motor connected to PIN 10
void setup(){ // Not necessary
void loop(){
for(value = 0; value <= 255; value +=5){
//generates a ramp of voltage from 0 to 255, i.e. from 0 to 5v
analogWrite (motor, value);
delay (30); // wait 30 ms to make the effect visible
}
for(value = 255; value >=0; value-=5){
// a down ramp from 255 to 0 voltage is generated that is 5 to 0v
analogWrite (motor, value);
delay (30);
}
}
To control the speed to our liking, i.e. using a potentiometer which is placed in
one of the analog inputs and based on the value that is read at the input, so the
motor rotates more or less fast.
21
Program
int value = 0; // a variable that contains the value to get analog input read
int motor = 10; // motor connected to PIN 10
int potentiometer = 0 ; // Set the analogue input
void setup(){ // Not necessary
void loop(){
value = analogRead (potentiometer); // reads the value of the analog input
and allocates val
analogWrite (motor, value); // The read value is sent to the analog output 0
delay (30); // wait 30 ms to make visible the effect
}
22
7. DC motor control using a L293D driver
With this application we will move a DC motor using a power IC, specific for these
applications. The circuit you can move up to two motors, well only do it with one.
In this Assembly, we can move the motor in both rotation directions, which we
couldnt with the previous assembly.
It will function as the first approach of the previous motor, i.e., lets create a power
surge and a descent ramp so motor change speed in automatic mode.
DC motor control or driver:
The two parameters that we want to control of a DC motor is its speed and its
rotation direction. The direction is controlled by changing the polarity. On the
other hand, for its speed, we must use modulation technique for PWM-pulse
width.
Here are some graphs showing the relationship between the pulse (PWM) signal
and the effective voltage:
23
When the pulse is active is half of the period of the signal or duty cycle parameter
is 50%, the effective voltage is half of the total input voltage.
When the duty cycle is reduced to 25%, the effective voltage is a quarter of the
total input voltage. Then the motor speed decreases.
Thus, by controlling the duty cycle or while the pulse is active (frequency), we
can control the DC motor speed.
A way to perform this check on Arduino, is using the PWM analog output.
You should remembered that the PWM output signal (pins 9, 10) is a constant
frequency signal (30769 Hz) and that only allows us to change the duty cycle
or the time that the pulse is active (on) or inactive (off), using the analogWrite()
function.
24
The other way is generating PWM signals using the microprocessor capability
through the function digitalWrite ().
If you want to simultaneously control the speed and direction of a motor, we need
to use an integrated circuit or chip, called in general, as H bridge , for example
the L293D.
Chip L293D/B (H-bridge):
It is an integrated circuit or chip that can be used to simultaneously control the
speed and direction of two DC motors (containing two H bridges). The difference
between L393D and L293B model is that the first comes with protection diodes
which avoid damage caused by the voltage spikes that the motor can cause.
It contains 4 digital pins (2, 7, 10, 15) to control the motor direction.
25
The enable (1, 9) pins support as input a PWM signal and it are used to control
the speed of the motors using pulse width modulation technique.
The motors are connected between pins 3, 6, 11 or 14. The Vss voltage is to feed
or give power to the motor.
Program
26
22
TXD314
RXD315
TXD216
RXD217
TXD118
RXD217
SDA 20
SCL 21
7
6
5
4
3
2
1
0
AREF
GND
13
12
11
10
9
8
PWM 24
COMMUNICATION 26
28
30
32
34
36
DIGITAL
38
40
42
44
46
48
50
52
POWER
IOREF
RESET
ANALOG IN
3V3
10
11
12
5V GND VIN
13
14
15
0
1
2
3
4
5
6
7
8
9
27
Program
Motor control with L293D driver
int value = 0; // a variable that contains the value
int motorFowards = 10; // Motor forward - > PIN 10
int motorBackwards = 11; // Motor recoil - > PIN 11
void setup() {} // Not necessary
void loop() {
analogWrite(motorBackwards, 0); // Motor forward... raises the speed
for(value = 0; value <= 255; value+=5) {
analogWrite (motorFowards, value);
delay (30);
}
for(value = 255; value >=0; value-=5) { // forward motor... lowers the speed
analogWrite (motorFowards, value);
delay (30);
}
analogWrite(motorFowards, 0); // Motor back... raises the speed
for(value = 0; value <= 255; value+=5) {
analogWrite (motor motorBackwards, value);
delay (30);
}
for(value = 255; value >=0; value-=5) { // motor backwards... lowers speed }
analogWrite (motorBackwards, value);
delay (30);
}
}
28
9. Use a relay to turn on 120 V devices
This example shows how to power a 120-Volt alternating current (AC) light bulb
through a circuit of 5 V DC (DC) ruled by the Arduino. It can be used with any
other circuit of 120 V, with a maximum of 10 A (with the relay of the example).
What is a relay?
The relay is an electromechanical device that functions as a switch controlled by
an electrical circuit in which, by means of an electromagnet, actuates a set of one
or more contacts that allow open or close other independent electrical circuits.
From here extract important information: we can separate two circuits in such a
way that they work with different voltages. One to 5 V (Arduino) and another 120
v (the bulb).
29
Program
/*
It turns on and off a 220 V light bulb every 2 seconds, using,
a relay connected to the Arduino PIN 8
*/
int relayPin = 8; // PIN to which the relay is connected
void setup() {
pinMode (relayPin, OUTPUT);
}
void loop() {
digitalWrite(relayPin, HIGH); // Power
delay (2000);
digitalWrite(relayPin, LOW); // Shutdown
delay (2000);
}
30
SPECIFICATIONS
Micro controller: MEGA32U4
Input: 5-12 V - - -
Operational frequency: 16 MHz
Analogue input ports: 12
Digital input / output ports: 20 (including PWM ports)
Flash memory capacity: 256 kB
SRAM: 2.5 kB
EEPROM: 1 kB
Boot loader: STK500v2
PWM output: Yes
Voltage output: 5 V - - -
Switch Reset: Yes
PC interface: USB
Software: Arduino
31
Product: PCB compatible with Arduino Leonardo
Part number: ARD-020
Brand: Steren
WARRANTY
This Steren product is warranted under normal usage against defects in workmanship
and materials to the original purchaser for one year from the date of purchase.
CONDITIONS
1. This warranty card with all the required information, invoice, product box or
package, and product, must be presented when warranty service is required.
2. If the product is in the warranty time, the company will repair it free of charge.
3. The repairing time will not exceed 30 natural days, from the day the claim was
received.
4. Steren sell parts, components, consumables and accessories to customer, as well
as warranty service, at any of the addresses mentioned later.
If the product has been damaged by an accident, acts of God, mishandling, leaky
batteries, failure to follow enclosed instructions, improper repair by unauthorized
personnel, improper safe keeping, among others.
a) The consumer can also claim the warranty service in the purchase establishment.
b) If you lose the warranty card, we can reissue it, if you show the invoice or purchase
ticket.
RETAILER INFORMATION
Name of the retailer In case your product fails
Address or have questions, please
Product contact your nearest dealer.
Brand If you are in Mexico, please
Part number call to our Call Center.
Serial number 01 800 500 9000
Date of delivery
32