Hacking.LibraryTutorial History

Hide minor edits - Show changes to markup

June 02, 2010, at 11:17 PM by Equipo Traduccion -
Changed lines 63-65 from:
  1. include "WProgram.h"

to:
  1. Include "WProgram.h"

Changed lines 68-70 from:
  1. ifndef Morse_h
  2. define Morse_h
to:
  1. Ifndef Morse_h
  2. Define Morse_h
Changed lines 73-75 from:
  1. endif

to:
  1. endif

Deleted line 81:

[@

Changed lines 96-97 from:
    void dot();
    void dash();
to:
    void punto();
    void raya();
Changed lines 103-117 from:

@]

Now let's go through the various parts of the source file, Morse.cpp.

First comes a couple of #include statements. These give the rest of the code access to the standard Arduino functions, and to the definitions in your header file:

#include "WProgram.h"
#include "Morse.h"

Then comes the constructor. Again, this explains what should happen when someone creates an instance of your class. In this case, the user specifies which pin they would like to use. We configure the pin as an output save it into a private variable for use in the other functions:

[@ Morse::Morse(int pin)

to:

Vamos a repasar las distintas partes del código fuente de Morse.cpp.

Lo primero son un par de # include. Con esto el resto del código tendrá acceso a las funciones estándar de Arduino, y a las definiciones definidas en Morse.h:

  1. Include "WProgram.h"
  2. Include "Morse.h"

A continuación viene el constructor. Una vez más, en el constructor se establece lo que debe ocurrir cuando alguien crea una instancia de la clase. En este caso, el usuario especifica el pin que le gustaría utilizar. Configuramos el pin como salida en una variable privada para su uso en las otras funciones:

MORSE:: Morse (pin int) (   pinMode (pin, OUTPUT);   _pin = pin; )

Hay un par de cosas extrañas en este código. La primera es el Morse:: antes del nombre de la función. Esto indica que la función es parte de la clase Morse. Verás esto en otras funciones de la clase. Lo segundo es el subrayado en el nombre de nuestra variable privada, _pin. Esta variable puede tener cualquier nombre, siempre y cuando coincida con la definición que figura en el archivo de encabezado. Agregar un subrayado al inicio del nombre es una convención común para dejar claro que las variables son privadas, y también para diferenciarlas del argumento de la función (el pin en este caso).

Después viene el código del programa que estamos convirtiendo en una librería (¡por fin!). Se ve más o menos lo mismo, salvo Morse:: delante de los nombres de las funciones, y en lugar de _pin pin:

void Morse::punto()

Changed lines 128-129 from:
  pinMode(pin, OUTPUT);
  _pin = pin;
to:
  digitalWrite(_pin, HIGH);
  delay(250);
  digitalWrite(_pin, LOW);
  delay(250);  
Changed lines 133-140 from:

@]

There are a couple of strange things in this code. First is the Morse:: before the name of the function. This says that the function is part of the Morse class. You'll see this again in the other functions in the class. The second unusual thing is the underscore in the name of our private variable, _pin. This variable can actually have any name you want, as long as it matches the definition in the header file. Adding an underscore to the start of the name is a common convention to make it clear which variables are private, and also to distinguish the name from that of the argument to the function (pin in this case).

Next comes the actual code from the sketch that you're turning into a library (finally!). It looks pretty much the same, except with Morse:: in front of the names of the functions, and _pin instead of pin:

[@ void Morse::dot()

to:

void Morse::raya()

Added lines 137-138:
  delay(1000);
  digitalWrite(_pin, LOW);
Deleted lines 139-140:
  digitalWrite(_pin, LOW);
  delay(250);  
Changed lines 142-153 from:

void Morse::dash()

to:

Por último, es típico incluir un comentario en la parte superior del código fuente. Vamos a ver el código:

/*

  Morse.cpp - Library for flashing Morse code.
  Created by David A. Mellis, November 2, 2007.
  Released into the public domain.
  • /

  1. include "WProgram.h"
  2. include "Morse.h"

Morse::Morse(int pin)

Added lines 155-160:
  pinMode(pin, OUTPUT);
  _pin = pin;

}

void Morse::punto() {

Deleted lines 161-162:
  delay(1000);
  digitalWrite(_pin, LOW);
Added lines 163-164:
  digitalWrite(_pin, LOW);
  delay(250);  
Changed lines 166-180 from:

@]

Finally, it's typical to include the comment header at the top of the source file as well. Let's see the whole thing:

[@ /*

  Morse.cpp - Library for flashing Morse code.
  Created by David A. Mellis, November 2, 2007.
  Released into the public domain.
  • /

  1. include "WProgram.h"
  2. include "Morse.h"

Morse::Morse(int pin)

to:

void Morse::raya()

Deleted lines 168-173:
  pinMode(pin, OUTPUT);
  _pin = pin;

}

void Morse::dot() {

Added lines 170-171:
  delay(1000);
  digitalWrite(_pin, LOW);
Deleted lines 172-173:
  digitalWrite(_pin, LOW);
  delay(250);  
Changed lines 175-186 from:

void Morse::dash()

to:

Y eso es todo lo que necesita (hay algunas otras cosas opcionales, pero hablaremos de eso más adelante). Vamos a ver cómo usar la librería.

En primer lugar, hay que crear el directorio Morse dentro del subdirectorio de librerías . Copia o mueve los archivos Morse.h y Morse.cpp a ese directorio. Ahora ejecuta el IDE de Arduino. Si vas al menú Sketch > Import Library deberías ver el una opción Morse. La librería será compilada con los programas que la utilizan. Si no aparece la librería, asegúrate de que los nombres de los archivos terminan realmente ten .cpp y .h (y no en .pde o .txt, por ejemplo).

Vamos a ver cómo podemos modificar nuestro programa de SOS para hacer uso de la nueva librería:

  1. include <Morse.h>

Morse morse(13);

void setup()

Deleted lines 187-190:
  digitalWrite(_pin, HIGH);
  delay(1000);
  digitalWrite(_pin, LOW);
  delay(250);
Changed lines 189-202 from:

@]

And that's all you need (there's some other nice optional stuff, but we'll talk about that later). Let's see how you use the library.

First, make a Morse directory inside of the libraries sub-directory of your sketchbook directory. Copy or move the Morse.h and Morse.cpp files into that directory. Now launch the Arduino environment. If you open the Sketch > Import Library menu, you should see Morse inside. The library will be compiled with sketches that use it. If the library doesn't seem to build, make sure that the files really end in .cpp and .h (with no extra .pde or .txt extension, for example).

Let's see how we can replicate our old SOS sketch using the new library:

[@

  1. include <Morse.h>

Morse morse(13);

void setup()

to:

void loop()

Added lines 192-195:
  morse.punto(); morse.punto(); morse.punto();
  morse.raya(); morse.raya(); morse.raya();
  morse.punto(); morse.punto(); morse.punto();
  delay(3000);
Changed lines 198-232 from:

void loop() {

  morse.dot(); morse.dot(); morse.dot();
  morse.dash(); morse.dash(); morse.dash();
  morse.dot(); morse.dot(); morse.dot();
  delay(3000);

} @]

There are a few differences from the old sketch (besides the fact that some of the code has moved to a library).

First, we've added an #include statement to the top of the sketch. This makes the Morse library available to the sketch and includes it in the code sent to the board. That means if you no longer need a library in a sketch, you should delete the #include statement to save space.

Second, we now create an instance of the Morse class called morse:

Morse morse(13);

When this line gets executed (which actually happens even before the setup() function), the constructor for the Morse class will be called, and passed the argument you've given here (in this case, just 13).

Notice that our setup() is now empty; that's because the call to pinMode() happens inside the library (when the instance is constructed).

Finally, to call the dot() and dash() functions, we need to prefix them with morse. - the name of the instance we want to use. We could have multiple instances of the Morse class, each on their own pin stored in the _pin private variable of that instance. By calling a function on a particular instance, we specify which instance's variables should be used during that call to a function. That is, if we had both:

Morse morse(13);
Morse morse2(12);

then inside a call to morse2.dot(), _pin would be 12.

If you tried the new sketch, you probably noticed that nothing from our library was recognized by the environment and highlighted in color. Unfortunately, the Arduino software can't automatically figure out what you've define in your library (though it would be a nice feature to have), so you have to give it a little help. To do this, create a file called keywords.txt in the Morse directory. It should look like this:

[@

to:

Hay algunas diferencias con el programa original (aparte del hecho de que parte del código se ha trasladado a la librería).

En primer lugar, hemos añadido una declaración # include al principio del programa. Esto hace que la librería Morse esté disponible para el programa y que se envíe a la placa de Arduino. Cuando ya no necesite una librería en un programa, debe eliminar la sentencia # include para ahorrar espacio.

En segundo lugar, creamos una instancia de la clase Morse llamada morse:

Morse morse(13);

Cuando esta línea se ejecute ( esto sucede incluso antes de que se ejecute la función setup () ), se llamará al constructor de la clase Morse, y se le pasará un parámetro (en este caso, el valor 13).

Tenga en cuenta que nuestro setup() está vacío, esto se debe a que la llamada a pinMode () se produce dentro de la librería (cuando se construye la instancia).

Por último, para llamar a las funciones punto() y raya(), tenemos que precederlas del prefijo morse (que es el nombre de la instancia que hemos creado). Podríamos tener varias instancias de la clase Morse, cada una con su propio PIN almacenado en la variable privada _pin de esa instancia. Al llamar a una función se indica que instancia de la clase se debe utilizar. Es decir, si tuviéramos:

Morse morse (13); Morse morse2 (12);

la llamada a morse2.dot (), hace que la salida sea por el pin 12.

Si pruebas el nuevo programa, probablemente te darás cuenta de que el IDE de Arduino no reconoce las funciones de la librería y no resalta el código. Por desgracia, por ahora el software de Arduino no puede averiguar lo que hay definido en la librería (aunque sería una buena característica a tener en cuenta), así que tienes que ayudarle un poco. Para ello, crea un archivo llamado keywords.txt en el directorio de Morse.. Que debe tener este aspecto:

Changed lines 220-230 from:

dash KEYWORD2 dot KEYWORD2 @]

Each line has the name of the keyword, followed by a tab (not spaces), followed by the kind of keyword. Classes should be KEYWORD1 and are colored orange; functions should be KEYWORD2 and will be brown. You'll have to restart the Arduino environment to get it to recognize the new keywords.

It's also nice to provide people with an example sketch that uses your library. To do this, create an examples directory inside the Morse directory. Then, move or copy the directory containing the sketch (let's call it SOS) we wrote above into the examples directory. (You can find the sketch using the Sketch > Show Sketch Folder command.) If you restart the Arduino environment (this is the last time, I promise) - you'll see a Library-Morse item inside the File > Sketchbook > Examples menu containing your example. You might want to add some comments that better explain how to use your library.

If you'd like to check out the complete library (with keywords and example), you can download it: Morse.zip.

That's all for now but I'll probably write an advanced library tutorial soon. In the meantime, if you have any problems or suggestions, please post them to the Software Development forum.

to:

raya KEYWORD2 punto KEYWORD2

Cada línea tiene el nombre de la palabra clave, seguido de un tabulador (no espacios), seguido por el tipo de palabra clave. Las clases deben ser del tipo KEYWORD1 y se muestran de color naranja; las funciones deben ser del tipo KEYWORD2 y serán de color marrón. Tendrá que reiniciar el entorno Arduino para conseguir que reconozca las nuevas palabras clave.

Es conveniente acompañar las librerías con algún programa de ejemplo que haga uso las mismas. Para ello, cree un directorio examples dentro del directorio Morse. A continuación, copie el directorio que contiene el programa de ejemplo que escribimos arriba (lo llamaremos SOS) en el directorio de ejemplos. (Puedes encontrar el programa de ejemplo con la opción Sketch > Show Sketch Folder) Si reinicias el entorno Arduino (esta es la última vez, lo prometo) – verás la opción Library-Morse dentro de File > Sketchbook > Examples que contiene su ejemplo. Es posible que quieras agregar algunos comentarios para explicar mejor cómo usar la librería.

Si quieres echa un vistazo a la librería completa (con palabras clave y el ejemplo), puede descargarlo: Morse.zip.

Eso es todo por ahora, pero probablemente voy a escribir una colección de tutoriales avanzados pronto. Mientras tanto, si tienes cualquier problema o sugerencia, por favor escribe en el foro de desarrollo de software.

June 01, 2010, at 11:07 PM by Equipo Traduccion -
Changed lines 63-65 from:
  1. Include "WProgram.h"

to:
  1. include "WProgram.h"

Changed lines 68-70 from:
  1. Ifndef Morse_h
  2. Define Morse_h
to:
  1. ifndef Morse_h
  2. define Morse_h
Changed lines 73-75 from:
  1. endif

to:
  1. endif

June 01, 2010, at 11:02 PM by Equipo Traduccion -
Changed lines 44-48 from:

You need at least two files for a library: a header file (w/ the extension .h) and the source file (w/ extension .cpp). The header file has definitions for the library: basically a listing of everything that's inside; while the source file has the actual code. We'll call our library "Morse", so our header file will be Morse.h. Let's take a look at what goes in it. It might seem a bit strange at first, but it will make more sense once you see the source file that goes with it.

The core of the header file consists of a line for each function in the library, wrapped up in a class along with any variables you need:

[@

to:

Para una librería necesita al menos dos arcivos: un archivo de cabecera (w / con extensión. H) y el código fuente (w / extensión. cpp). El archivo de cabecera contiene definiciones para la librería: básicamente un listado de todo lo que hay dentro, mientras que el archivo del código fuente tiene el código real. Vamos a llamar a nuestra librería "Morse", por lo que nuestro archivo de cabecera será Morse.h. Echemos un vistazo a lo que contiene. Puede parecer un poco extraño al principio, pero tendrá más sentido una vez que vea el código fuente que lo acompaña.

El archivo de cabecera consiste básicamente en una clase con una línea para cada función de la librería, junto con las variables que se van a usar:

Changed lines 52-53 from:
    void dot();
    void dash();
to:
    void punto();
    void raya();
Changed lines 57-62 from:

@]

A class is simply a collection of functions and variables that are all kept together in one place. These functions and variables can be public, meaning that they can be accessed by people using your library, or private, meaning they can only be accessed from within the class itself. Each class has a special function known as a constructor, which is used to create an instance of the class. The constructor has the same name as the class, and no return type.

You need a couple of other things in the header file. One is an #include statement that gives you access to the standard types and constants of the Arduino language (this is automatically added to normal sketches, but not to libraries). It looks like this (and goes above the class definition given previously):

to:

Una clase es simplemente una colección de funciones y variables agrupadas en un mismo lugar. Estas funciones y variables pueden ser públicas, lo que significa que las podrán usar las personas que están utilizando la librería, o privada, lo que significa que sólo se puede acceder a ellas desde la propia clase. Cada clase tiene una función especial conocida como constructor, que se utiliza para crear una instancia de la clase (o sea, un objeto). El constructor tiene el mismo nombre que la clase, y no devuelve nada.

Se necesitan un par cosas más en el archivo de encabezado. Una de ellas es una instrucción # include que da acceso a los tipos estándar y las constantes del lenguaje Arduino (esto se agrega automáticamente a los programas normales, pero no a las librerías). Se parece a esto (y se coloca antes de la definición de la clase mostrada anteriormente):

  1. Include "WProgram.h"

Por último, es común añadir las siguientes lineas de código :

  1. Ifndef Morse_h
  2. Define Morse_h

// La declaración # include y el código van aquí ...

  1. endif

Básicamente, esto evita problemas si alguien accidentalmente usa dos veces el #include con la librería que estamos construyendo, evitando que se declaren las variables y funciones más de una vez.

Por último, se suele poner un comentario en la parte superior de la librería con su nombre, una breve descripción de lo que hace, quién lo escribió, la fecha y el tipo de licencia.

Echemos un vistazo a la cabecera completa:

Added lines 83-90:

/*

  Morse.h - Library for flashing Morse code.
  Created by David A. Mellis, November 2, 2007.
  Released into the public domain.
  • /
  1. ifndef Morse_h
  2. define Morse_h
Added lines 92-103:

class Morse {

  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;

};

  1. endif
Changed lines 106-107 from:

Finally, it's common to wrap the whole header file up in a weird looking construct:

to:

Now let's go through the various parts of the source file, Morse.cpp.

First comes a couple of #include statements. These give the rest of the code access to the standard Arduino functions, and to the definitions in your header file:

Changed lines 111-116 from:
  1. ifndef Morse_h
  2. define Morse_h

// the #include statment and code go here...

  1. endif
to:
  1. include "WProgram.h"
  2. include "Morse.h"
Changed lines 115-120 from:

Basically, this prevents problems if someone accidently #include's your library twice.

Finally, you usually put a comment at the top of the library with its name, a short description of what it does, who wrote it, the date, and the license.

Let's take a look at the complete header file:

to:

Then comes the constructor. Again, this explains what should happen when someone creates an instance of your class. In this case, the user specifies which pin they would like to use. We configure the pin as an output save it into a private variable for use in the other functions:

Changed lines 118-128 from:

/*

  Morse.h - Library for flashing Morse code.
  Created by David A. Mellis, November 2, 2007.
  Released into the public domain.
  • /
  1. ifndef Morse_h
  2. define Morse_h

  3. include "WProgram.h"

class Morse

to:

Morse::Morse(int pin)

Changed lines 120-128 from:
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;

};

  1. endif
to:
  pinMode(pin, OUTPUT);
  _pin = pin;

}

Changed lines 125-128 from:

Now let's go through the various parts of the source file, Morse.cpp.

First comes a couple of #include statements. These give the rest of the code access to the standard Arduino functions, and to the definitions in your header file:

to:

There are a couple of strange things in this code. First is the Morse:: before the name of the function. This says that the function is part of the Morse class. You'll see this again in the other functions in the class. The second unusual thing is the underscore in the name of our private variable, _pin. This variable can actually have any name you want, as long as it matches the definition in the header file. Adding an underscore to the start of the name is a common convention to make it clear which variables are private, and also to distinguish the name from that of the argument to the function (pin in this case).

Next comes the actual code from the sketch that you're turning into a library (finally!). It looks pretty much the same, except with Morse:: in front of the names of the functions, and _pin instead of pin:

Changed lines 130-137 from:
  1. include "WProgram.h"
  2. include "Morse.h"

@]

Then comes the constructor. Again, this explains what should happen when someone creates an instance of your class. In this case, the user specifies which pin they would like to use. We configure the pin as an output save it into a private variable for use in the other functions:

[@ Morse::Morse(int pin)

to:

void Morse::dot()

Changed lines 132-133 from:
  pinMode(pin, OUTPUT);
  _pin = pin;
to:
  digitalWrite(_pin, HIGH);
  delay(250);
  digitalWrite(_pin, LOW);
  delay(250);  
Added lines 137-144:

void Morse::dash() {

  digitalWrite(_pin, HIGH);
  delay(1000);
  digitalWrite(_pin, LOW);
  delay(250);

}

Changed lines 147-150 from:

There are a couple of strange things in this code. First is the Morse:: before the name of the function. This says that the function is part of the Morse class. You'll see this again in the other functions in the class. The second unusual thing is the underscore in the name of our private variable, _pin. This variable can actually have any name you want, as long as it matches the definition in the header file. Adding an underscore to the start of the name is a common convention to make it clear which variables are private, and also to distinguish the name from that of the argument to the function (pin in this case).

Next comes the actual code from the sketch that you're turning into a library (finally!). It looks pretty much the same, except with Morse:: in front of the names of the functions, and _pin instead of pin:

to:

Finally, it's typical to include the comment header at the top of the source file as well. Let's see the whole thing:

Changed lines 150-159 from:

void Morse::dot()

to:

/*

  Morse.cpp - Library for flashing Morse code.
  Created by David A. Mellis, November 2, 2007.
  Released into the public domain.
  • /

  1. include "WProgram.h"
  2. include "Morse.h"

Morse::Morse(int pin)

Added lines 161-166:
  pinMode(pin, OUTPUT);
  _pin = pin;

}

void Morse::dot() {

Changed lines 182-183 from:

Finally, it's typical to include the comment header at the top of the source file as well. Let's see the whole thing:

to:

And that's all you need (there's some other nice optional stuff, but we'll talk about that later). Let's see how you use the library.

First, make a Morse directory inside of the libraries sub-directory of your sketchbook directory. Copy or move the Morse.h and Morse.cpp files into that directory. Now launch the Arduino environment. If you open the Sketch > Import Library menu, you should see Morse inside. The library will be compiled with sketches that use it. If the library doesn't seem to build, make sure that the files really end in .cpp and .h (with no extra .pde or .txt extension, for example).

Let's see how we can replicate our old SOS sketch using the new library:

Changed lines 189-198 from:

/*

  Morse.cpp - Library for flashing Morse code.
  Created by David A. Mellis, November 2, 2007.
  Released into the public domain.
  • /

  1. include "WProgram.h"
  2. include "Morse.h"

Morse::Morse(int pin)

to:
  1. include <Morse.h>

Morse morse(13);

void setup()

Deleted lines 194-195:
  pinMode(pin, OUTPUT);
  _pin = pin;
Changed line 197 from:

void Morse::dot()

to:

void loop()

Changed lines 199-202 from:
  digitalWrite(_pin, HIGH);
  delay(250);
  digitalWrite(_pin, LOW);
  delay(250);  
to:
  morse.dot(); morse.dot(); morse.dot();
  morse.dash(); morse.dash(); morse.dash();
  morse.dot(); morse.dot(); morse.dot();
  delay(3000);
Deleted lines 203-210:

void Morse::dash() {

  digitalWrite(_pin, HIGH);
  delay(1000);
  digitalWrite(_pin, LOW);
  delay(250);

}

Changed lines 206-211 from:

And that's all you need (there's some other nice optional stuff, but we'll talk about that later). Let's see how you use the library.

First, make a Morse directory inside of the libraries sub-directory of your sketchbook directory. Copy or move the Morse.h and Morse.cpp files into that directory. Now launch the Arduino environment. If you open the Sketch > Import Library menu, you should see Morse inside. The library will be compiled with sketches that use it. If the library doesn't seem to build, make sure that the files really end in .cpp and .h (with no extra .pde or .txt extension, for example).

Let's see how we can replicate our old SOS sketch using the new library:

to:

There are a few differences from the old sketch (besides the fact that some of the code has moved to a library).

First, we've added an #include statement to the top of the sketch. This makes the Morse library available to the sketch and includes it in the code sent to the board. That means if you no longer need a library in a sketch, you should delete the #include statement to save space.

Second, we now create an instance of the Morse class called morse:

Deleted lines 212-213:
  1. include <Morse.h>
Deleted lines 213-224:

void setup() { }

void loop() {

  morse.dot(); morse.dot(); morse.dot();
  morse.dash(); morse.dash(); morse.dash();
  morse.dot(); morse.dot(); morse.dot();
  delay(3000);

}

Deleted lines 215-224:

There are a few differences from the old sketch (besides the fact that some of the code has moved to a library).

First, we've added an #include statement to the top of the sketch. This makes the Morse library available to the sketch and includes it in the code sent to the board. That means if you no longer need a library in a sketch, you should delete the #include statement to save space.

Second, we now create an instance of the Morse class called morse:

Morse morse(13);

June 01, 2010, at 10:28 PM by Equipo Traduccion - tamos en ello
Changed lines 1-7 from:

Writing a Library for Arduino

This document explains how to create a library for Arduino. It starts with a sketch with a sketch for flashing Morse code and explains how to convert its functions into a library. This allows other people to easily use the code that you've written and to easily update it as you improve the library.

We start with a sketch that does simple Morse code:

[@

to:

Escribir una librería para Arduino

Este documento explica cómo crear una librería para Arduino. Se inicia con un programa de código Morse y explica cómo convertir sus funciones en una librería. Esto permite que otras personas usen el código que has escrito y puedan actualizarlo facilmente a medida que mejora la librería.

Comenzamos con un programa de código Morse:

Changed lines 16-18 from:
  dot(); dot(); dot();
  dash(); dash(); dash();
  dot(); dot(); dot();
to:
  punto(); punto(); punto();
  raya(); raya(); raya();
  punto(); punto(); punto();
Changed line 22 from:

void dot()

to:

void punto()

Changed line 30 from:

void dash()

to:

void raya()

Changed lines 37-44 from:

@]

If you run this sketch, it will flash out the code for SOS (a distress call) on pin 13.

The sketch has a few different parts that we'll need to bring into our library. First, of course, we have the dot() and dash() functions that do the actual blinking. Second, there's the ledPin variable which the functions use to determine which pin to use. Finally, there's the call to pinMode() that initializes the pin as an output.

Let's start turning the sketch into a library!

to:

Si ejecuta este programa, se representará el código de SOS (llamada de auxilio) en el pin 13.

El programa tiene unas pocas partes que tendremos que poner en nuestra librería. En primer lugar, tenemos las funciones punto() y raya() que hacen el parpadeo. En segundo lugar, tenemos la variable ledPin que indica el pin a utilizar. Por último, está la llamada a pinMod () que inicializa el pin como salida.

Vamos a empezar a convertir el programa en una librería!

February 02, 2010, at 09:40 PM by David A. Mellis -
Changed lines 189-190 from:

First, make a Morse directory inside of the hardware/libraries sub-directory of the Arduino application directory. Copy or move the Morse.h and Morse.cpp files into that directory. Now launch the Arduino environment. When it starts, it will compile your library, generating an object file (Morse.o) and displaying any warnings or errors. If you open the Sketch > Import Library menu, you should see Morse inside. As you work on your library, you'll need to delete the Morse.o file and relaunch the Arduino environment (or pick a new board from the Tools > Boards menu) to recompile your library. If the library doesn't seem to build, make sure that the files really end in .cpp and .h (with no extra .pde or .txt extension, for example).

to:

First, make a Morse directory inside of the libraries sub-directory of your sketchbook directory. Copy or move the Morse.h and Morse.cpp files into that directory. Now launch the Arduino environment. If you open the Sketch > Import Library menu, you should see Morse inside. The library will be compiled with sketches that use it. If the library doesn't seem to build, make sure that the files really end in .cpp and .h (with no extra .pde or .txt extension, for example).

May 24, 2009, at 04:06 PM by David A. Mellis -
Changed line 67 from:
  1. include "WConstants.h"
to:
  1. include "WProgram.h"
Changed lines 96-97 from:
  1. include "WConstants.h"
to:
  1. include "WProgram.h"
January 15, 2008, at 04:48 PM by David A. Mellis -
Changed lines 189-190 from:

First, make a Morse directory inside of the hardware/libraries sub-directory of the Arduino application directory. Copy or move the Morse.h and Morse.cpp files into that directory. Now launch the Arduino environment. When it starts, it will compile your library, generating an object file (Morse.o) and displaying any warnings or errors. If you open the Sketch > Import Library menu, you should see Morse inside. As you work on your library, you'll need to delete the Morse.o file and relaunch the Arduino environment (or pick a new board from the Tools > Boards menu) to recompile your library.

to:

First, make a Morse directory inside of the hardware/libraries sub-directory of the Arduino application directory. Copy or move the Morse.h and Morse.cpp files into that directory. Now launch the Arduino environment. When it starts, it will compile your library, generating an object file (Morse.o) and displaying any warnings or errors. If you open the Sketch > Import Library menu, you should see Morse inside. As you work on your library, you'll need to delete the Morse.o file and relaunch the Arduino environment (or pick a new board from the Tools > Boards menu) to recompile your library. If the library doesn't seem to build, make sure that the files really end in .cpp and .h (with no extra .pde or .txt extension, for example).

January 15, 2008, at 04:43 PM by David A. Mellis -
Added lines 246-247:

If you'd like to check out the complete library (with keywords and example), you can download it: Morse.zip.

November 02, 2007, at 10:01 PM by David A. Mellis -
Changed lines 244-246 from:

It's also nice to provide people with an example sketch that uses your library. To do this, create an examples directory inside the Morse directory. Then, move or copy the directory containing the sketch (let's call it SOS) we wrote above into the examples directory. (You can find the sketch using the Sketch > Show Sketch Folder command.) If you restart the Arduino environment (this is the last time, I promise) - you'll see a Library-Morse item inside the File > Sketchbook > Examples menu containing your example. You might want to add some comments that better explain how to use your library.

to:

It's also nice to provide people with an example sketch that uses your library. To do this, create an examples directory inside the Morse directory. Then, move or copy the directory containing the sketch (let's call it SOS) we wrote above into the examples directory. (You can find the sketch using the Sketch > Show Sketch Folder command.) If you restart the Arduino environment (this is the last time, I promise) - you'll see a Library-Morse item inside the File > Sketchbook > Examples menu containing your example. You might want to add some comments that better explain how to use your library.

That's all for now but I'll probably write an advanced library tutorial soon. In the meantime, if you have any problems or suggestions, please post them to the Software Development forum.

November 02, 2007, at 09:55 PM by David A. Mellis -
November 02, 2007, at 09:54 PM by David A. Mellis -
Changed lines 189-190 from:

First, make a Morse directory inside of the hardware/libraries sub-directory of the Arduino application directory. Copy or move the Morse.h and Morse.cpp files into that directory. Now launch the Arduino environment. When it starts, it will compile your library, generating an object file (Morse.o) and displaying any warnings or errors. If you open the Sketch > Import Library menu, you should see Morse inside.

to:

First, make a Morse directory inside of the hardware/libraries sub-directory of the Arduino application directory. Copy or move the Morse.h and Morse.cpp files into that directory. Now launch the Arduino environment. When it starts, it will compile your library, generating an object file (Morse.o) and displaying any warnings or errors. If you open the Sketch > Import Library menu, you should see Morse inside. As you work on your library, you'll need to delete the Morse.o file and relaunch the Arduino environment (or pick a new board from the Tools > Boards menu) to recompile your library.

Changed lines 234-235 from:

If you tried the new sketch, you probably noticed that nothing from our library was recognized by the environment and highlighted in color. Unfortunately, the Arduino software can't automatically figure out what you've define in your library (though it would be a nice feature to have), so you have to give it a little help. To do this, create a file called keywords.txt in the Morse directory. It should look like this:

to:

If you tried the new sketch, you probably noticed that nothing from our library was recognized by the environment and highlighted in color. Unfortunately, the Arduino software can't automatically figure out what you've define in your library (though it would be a nice feature to have), so you have to give it a little help. To do this, create a file called keywords.txt in the Morse directory. It should look like this:

Changed line 244 from:
to:

It's also nice to provide people with an example sketch that uses your library. To do this, create an examples directory inside the Morse directory. Then, move or copy the directory containing the sketch (let's call it SOS) we wrote above into the examples directory. (You can find the sketch using the Sketch > Show Sketch Folder command.) If you restart the Arduino environment (this is the last time, I promise) - you'll see a Library-Morse item inside the File > Sketchbook > Examples menu containing your example. You might want to add some comments that better explain how to use your library.

November 02, 2007, at 09:48 PM by David A. Mellis -
Changed lines 234-244 from:
to:

If you tried the new sketch, you probably noticed that nothing from our library was recognized by the environment and highlighted in color. Unfortunately, the Arduino software can't automatically figure out what you've define in your library (though it would be a nice feature to have), so you have to give it a little help. To do this, create a file called keywords.txt in the Morse directory. It should look like this:

Morse	KEYWORD1
dash	KEYWORD2
dot	KEYWORD2

Each line has the name of the keyword, followed by a tab (not spaces), followed by the kind of keyword. Classes should be KEYWORD1 and are colored orange; functions should be KEYWORD2 and will be brown. You'll have to restart the Arduino environment to get it to recognize the new keywords.

November 02, 2007, at 09:29 PM by David A. Mellis -
Changed lines 228-229 from:

Morse morseA(13); Morse morseB(12);

to:

Morse morse(13); Morse morse2(12);

Changed lines 232-234 from:

then inside a call to morseB.dot(), _pin would be 12.

to:

then inside a call to morse2.dot(), _pin would be 12.

November 02, 2007, at 09:29 PM by David A. Mellis -
Changed lines 193-234 from:
to:
#include <Morse.h>

Morse morse(13);

void setup()
{
}

void loop()
{
  morse.dot(); morse.dot(); morse.dot();
  morse.dash(); morse.dash(); morse.dash();
  morse.dot(); morse.dot(); morse.dot();
  delay(3000);
}

There are a few differences from the old sketch (besides the fact that some of the code has moved to a library).

First, we've added an #include statement to the top of the sketch. This makes the Morse library available to the sketch and includes it in the code sent to the board. That means if you no longer need a library in a sketch, you should delete the #include statement to save space.

Second, we now create an instance of the Morse class called morse:

Morse morse(13);

When this line gets executed (which actually happens even before the setup() function), the constructor for the Morse class will be called, and passed the argument you've given here (in this case, just 13).

Notice that our setup() is now empty; that's because the call to pinMode() happens inside the library (when the instance is constructed).

Finally, to call the dot() and dash() functions, we need to prefix them with morse. - the name of the instance we want to use. We could have multiple instances of the Morse class, each on their own pin stored in the _pin private variable of that instance. By calling a function on a particular instance, we specify which instance's variables should be used during that call to a function. That is, if we had both:

Morse morseA(13);
Morse morseB(12);

then inside a call to morseB.dot(), _pin would be 12.

November 02, 2007, at 09:18 PM by David A. Mellis -
Changed lines 185-187 from:

@]

to:

@]

And that's all you need (there's some other nice optional stuff, but we'll talk about that later). Let's see how you use the library.

First, make a Morse directory inside of the hardware/libraries sub-directory of the Arduino application directory. Copy or move the Morse.h and Morse.cpp files into that directory. Now launch the Arduino environment. When it starts, it will compile your library, generating an object file (Morse.o) and displaying any warnings or errors. If you open the Sketch > Import Library menu, you should see Morse inside.

Let's see how we can replicate our old SOS sketch using the new library:

November 02, 2007, at 09:10 PM by David A. Mellis -
Changed lines 152-187 from:
to:

Finally, it's typical to include the comment header at the top of the source file as well. Let's see the whole thing:

/*
  Morse.cpp - Library for flashing Morse code.
  Created by David A. Mellis, November 2, 2007.
  Released into the public domain.
*/

#include "WProgram.h"
#include "Morse.h"

Morse::Morse(int pin)
{
  pinMode(pin, OUTPUT);
  _pin = pin;
}

void Morse::dot()
{
  digitalWrite(_pin, HIGH);
  delay(250);
  digitalWrite(_pin, LOW);
  delay(250);  
}

void Morse::dash()
{
  digitalWrite(_pin, HIGH);
  delay(1000);
  digitalWrite(_pin, LOW);
  delay(250);
}



November 02, 2007, at 09:08 PM by David A. Mellis -
Added lines 132-152:

Next comes the actual code from the sketch that you're turning into a library (finally!). It looks pretty much the same, except with Morse:: in front of the names of the functions, and _pin instead of pin:

void Morse::dot()
{
  digitalWrite(_pin, HIGH);
  delay(250);
  digitalWrite(_pin, LOW);
  delay(250);  
}

void Morse::dash()
{
  digitalWrite(_pin, HIGH);
  delay(1000);
  digitalWrite(_pin, LOW);
  delay(250);
}

November 02, 2007, at 09:05 PM by David A. Mellis -
Changed lines 64-65 from:

You need a couple of other things in the header file. One is an #include statement that gives you access to the standard features of the Arduino language (this is automatically added to normal sketches, but not to libraries). It looks like this (and goes above the class definition given previously):

to:

You need a couple of other things in the header file. One is an #include statement that gives you access to the standard types and constants of the Arduino language (this is automatically added to normal sketches, but not to libraries). It looks like this (and goes above the class definition given previously):

Changed lines 111-131 from:
to:

Now let's go through the various parts of the source file, Morse.cpp.

First comes a couple of #include statements. These give the rest of the code access to the standard Arduino functions, and to the definitions in your header file:

#include "WProgram.h"
#include "Morse.h"

Then comes the constructor. Again, this explains what should happen when someone creates an instance of your class. In this case, the user specifies which pin they would like to use. We configure the pin as an output save it into a private variable for use in the other functions:

Morse::Morse(int pin)
{
  pinMode(pin, OUTPUT);
  _pin = pin;
}

There are a couple of strange things in this code. First is the Morse:: before the name of the function. This says that the function is part of the Morse class. You'll see this again in the other functions in the class. The second unusual thing is the underscore in the name of our private variable, _pin. This variable can actually have any name you want, as long as it matches the definition in the header file. Adding an underscore to the start of the name is a common convention to make it clear which variables are private, and also to distinguish the name from that of the argument to the function (pin in this case).

November 02, 2007, at 08:52 PM by David A. Mellis -
November 02, 2007, at 08:52 PM by David A. Mellis -
Changed lines 46-47 from:

You need at least two files for a library: a header file (w/ the extension .h) and the source file (w/ extension .cpp). The header file has definitions for the library: basically a listing of everything that's inside; while the source file has the actual code. We'll call our library "Morse", so our header file will be Morse.h. Let's take a look at what goes in it.

to:

You need at least two files for a library: a header file (w/ the extension .h) and the source file (w/ extension .cpp). The header file has definitions for the library: basically a listing of everything that's inside; while the source file has the actual code. We'll call our library "Morse", so our header file will be Morse.h. Let's take a look at what goes in it. It might seem a bit strange at first, but it will make more sense once you see the source file that goes with it.

Changed lines 62-111 from:

A class is simply a collection of functions and variables that are all kept together in one place. These functions and variables can be public, meaning that they can be accessed by people using your library, or private, meaning they can only be accessed from within the class itself. Each class has a special function known as a constructor, which is used to create an instance of the class. The constructor has the same name as the class, and no return type.

to:

A class is simply a collection of functions and variables that are all kept together in one place. These functions and variables can be public, meaning that they can be accessed by people using your library, or private, meaning they can only be accessed from within the class itself. Each class has a special function known as a constructor, which is used to create an instance of the class. The constructor has the same name as the class, and no return type.

You need a couple of other things in the header file. One is an #include statement that gives you access to the standard features of the Arduino language (this is automatically added to normal sketches, but not to libraries). It looks like this (and goes above the class definition given previously):

#include "WConstants.h"

Finally, it's common to wrap the whole header file up in a weird looking construct:

#ifndef Morse_h
#define Morse_h

// the #include statment and code go here...

#endif

Basically, this prevents problems if someone accidently #include's your library twice.

Finally, you usually put a comment at the top of the library with its name, a short description of what it does, who wrote it, the date, and the license.

Let's take a look at the complete header file:

/*
  Morse.h - Library for flashing Morse code.
  Created by David A. Mellis, November 2, 2007.
  Released into the public domain.
*/
#ifndef Morse_h
#define Morse_h

#include "WConstants.h"

class Morse
{
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;
};

#endif

November 02, 2007, at 08:43 PM by David A. Mellis -
Changed lines 46-47 from:

You need at least two files for a library: a header file (w/ the extension .h) and the source file (w/ extension .cpp). We'll call our library "Morse", so our header file will be Morse.h. Let's take a look at what goes in it.

to:

You need at least two files for a library: a header file (w/ the extension .h) and the source file (w/ extension .cpp). The header file has definitions for the library: basically a listing of everything that's inside; while the source file has the actual code. We'll call our library "Morse", so our header file will be Morse.h. Let's take a look at what goes in it.

Changed line 58 from:
    int pin;
to:
    int _pin;
Changed line 62 from:
to:

A class is simply a collection of functions and variables that are all kept together in one place. These functions and variables can be public, meaning that they can be accessed by people using your library, or private, meaning they can only be accessed from within the class itself. Each class has a special function known as a constructor, which is used to create an instance of the class. The constructor has the same name as the class, and no return type.

November 02, 2007, at 08:38 PM by David A. Mellis -
Changed lines 8-9 from:

int ledPin = 13;

to:

int pin = 13;

Changed line 12 from:
  pinMode(ledPin, OUTPUT);
to:
  pinMode(pin, OUTPUT);
Changed line 25 from:
  digitalWrite(ledPin, HIGH);
to:
  digitalWrite(pin, HIGH);
Changed line 27 from:
  digitalWrite(ledPin, LOW);
to:
  digitalWrite(pin, LOW);
Changed line 33 from:
  digitalWrite(ledPin, HIGH);
to:
  digitalWrite(pin, HIGH);
Changed line 35 from:
  digitalWrite(ledPin, LOW);
to:
  digitalWrite(pin, LOW);
Changed lines 44-62 from:
to:

Let's start turning the sketch into a library!

You need at least two files for a library: a header file (w/ the extension .h) and the source file (w/ extension .cpp). We'll call our library "Morse", so our header file will be Morse.h. Let's take a look at what goes in it.

The core of the header file consists of a line for each function in the library, wrapped up in a class along with any variables you need:

class Morse
{
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int pin;
};

November 02, 2007, at 08:30 PM by David A. Mellis -
Added lines 1-44:

Writing a Library for Arduino

This document explains how to create a library for Arduino. It starts with a sketch with a sketch for flashing Morse code and explains how to convert its functions into a library. This allows other people to easily use the code that you've written and to easily update it as you improve the library.

We start with a sketch that does simple Morse code:

int ledPin = 13;

void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  dot(); dot(); dot();
  dash(); dash(); dash();
  dot(); dot(); dot();
  delay(3000);
}

void dot()
{
  digitalWrite(ledPin, HIGH);
  delay(250);
  digitalWrite(ledPin, LOW);
  delay(250);
}

void dash()
{
  digitalWrite(ledPin, HIGH);
  delay(1000);
  digitalWrite(ledPin, LOW);
  delay(250);
}

If you run this sketch, it will flash out the code for SOS (a distress call) on pin 13.

The sketch has a few different parts that we'll need to bring into our library. First, of course, we have the dot() and dash() functions that do the actual blinking. Second, there's the ledPin variable which the functions use to determine which pin to use. Finally, there's the call to pinMode() that initializes the pin as an output.

Share