Como Criar Library pro Arduino
  December 3rd, 2009 by Rafael Quines

Este post tem o intuito de explicar como criar uma library pro Arduino. Tudo começa em um sketch com um esboço para piscar o código Morse e explica como converter as suas funções em uma biblioteca. Isso permite que outras pessoas facilmente possam usar o código que você escreveu e atualizá-lo quando você melhorar a biblioteca.

Sketch que pisca o código Morse:

int pin = 13;

void setup()
  pinMode(pin, OUTPUT);

void loop()
  dot(); dot(); dot();
  dash(); dash(); dash();
  dot(); dot(); dot();

void dot()
  digitalWrite(pin, HIGH);
  digitalWrite(pin, LOW);

void dash()
  digitalWrite(pin, HIGH);
  digitalWrite(pin, LOW);

Nesse sketch existem diferentes partes que precisaremos implementar para que o led pisque. Primeiramente temos os métodos dot() e dash() que são os responsáveis por fazer o led piscar na velocidade de um ponto, e um traço. Segundo, existe uma variável ledPin que determina qual o pino do Arduino estará sendo usado para ligar o led. E finalmente o pinMode que define que o pino será uma saída (OUTPUT).

Para criarmos nossa library, precisaremos obrigatoriamente de 2 (dois) arquivos: um arquivo de header (extensão “.h”) e o arquivo do código-fonte (extensão “.cpp”). Vamos começar então pelo arquivo Morse.h.

A primeira coisa a fazer é dar um include que dá acesso aos recursos padrões do arduino, como pinMode(), digitalWrite(), etc. Outra coisa a se fazer também é usar um “#ifndef” para impedir que, por algum motivo, alguém faça um include da sua classe mais de uma vez. Segue o código:

#ifndef Morse_h
#define Morse_h

#include "WProgram.h"
class Morse
    Morse(int pin);
    void dot();
    void dash();
    int _pin;


Agora vamos para o arquivo Morse.cpp. Devemos lembrar que este também precisa dar o include no WProgram.h, e no Morse.h. O objetivo desse cpp é dar a implementação de cada método definido no Morse.h.

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

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

void Morse::dot()
  digitalWrite(_pin, HIGH);
  digitalWrite(_pin, LOW);

void Morse::dash()
  digitalWrite(_pin, HIGH);
  digitalWrite(_pin, LOW);

Nossa library está pronta. Isso é tudo que precisamos. Agora veremos como usar nossa library recem criada.

Primeiro, devemos criar um diretório chamado Morse dentro das libraries do Arduino (hardware/libraries). Copie ou mova os arquivos Morse.h e Morse.cpp para este diretório. Agora abra a IDE do Arduino. No start da IDE, ela se encarregará de compilar nossa library, gerando um arquivo objeto (Morse.o) e mostrará warnings e erros. Se você abrir no menu Sketch -> Import Library você verá a Morse para ser incluída no seu sketch. Para qualquer alteração na library, precisamos excluir o arquivo Morse.o, fechar a IDE e abrir novamente, para que seja criado um novo arquivo Morse.o.

Agora um exemplo de sketch usando nossa library:


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();

Além da criação da nossa library, podemos ainda criar um exemplo de uso, para facilitar a vida do usuário que for usá-la. Para isso, criamos uma pasta chamada examples dentro do nosso diretório Morse. Então copie ou mova o diretório onde contem o sketch de exemplo. Reabrindo a IDE, você notará que o exemplo estará disponível no menu File -> Sketchbook -> Examples

Caso você queira baixar a library completa, faça o download AQUI.

Fonte: arduino.cc

This entry was posted on Thursday, December 3rd, 2009 at 11:58 and is filed under Arduino. You can follow any responses to this entry through the RSS 2.0 feed.You can leave a response, or trackback from your own site.

28 comentários

September 17th, 2012 at 21:34
Eduardo disse:

Excelente post, muito bom.

May 18th, 2013 at 21:26
www.chinasingels.com disse:

These are truly great ideas in regarding blogging. You have
touched some good points here. Any way keep up wrinting.

May 19th, 2013 at 1:07
digital publishing disse:

Hi mates, good paragraph and nice arguments commented at this
place, I am truly enjoying by these.

June 7th, 2013 at 6:54
discount-wall-decor.fashionarticles.eu disse:

Why viewers still make use of to read news papers when in this technological globe the whole thing is existing on net?

June 19th, 2013 at 2:01
Pomysł Na Firmę disse:

I know this website offers quality dependent articles and additional
material, is there any other web site which gives these kinds
of things in quality?

June 23rd, 2013 at 15:16
nidbvwjmamlr disse:


June 23rd, 2013 at 15:16
shkpxvdqzblj disse:


June 25th, 2013 at 14:21
Deepak disse:

Hi, Thanks for the comment on my blog post The Idle Functional consultant. I see here some comments that look like spam. Don’t you use any anti spam tool on your blog…. just curious.

July 25th, 2013 at 1:27
ablehostel.com disse:

Hi there this is kinda of off topic but I
was wondering if blogs use WYSIWYG editors or if you have to manually
code with HTML. I’m starting a blog soon but have no coding expertise so I wanted to get advice from someone with experience. Any help would be enormously appreciated!

October 8th, 2013 at 19:01
coby internet tablet disse:

Organic virgin coconut oil over your favorite salads to enhance the aroma and texture.
Basically, you can cook anything and in any case, it is
coconut oil for eczema important to note that one of the healthiest dietary oils
on the planet. After a week and if you have ever heard of HAARP, but please, do yourself
a favor and google that, as well as might be employed within salad dressing.

October 9th, 2013 at 19:39
protein powder disse:

This one of a kind manufacturing process allows
the body to enhance best protein powder for weight loss the diet and exercise plan.

Each type of powder are phosphorus-containing proteins and make up 80 percent of
this in cow’s milk, whey protein concentrate, hydrolysed whey protein, soy protein, blend

November 13th, 2013 at 13:13
furniture financing online disse:

Heya! Ijust wanted to ask if you ever have any troublke with hackers?
My last blog (wordpress) was hacked and I enfed up losing a few months off hard work due to nno back up.
Do you have aany soolutions to stop hackers?

February 14th, 2014 at 10:30
cardiac disse:

We are a gaggle of volunteers and opening a brand new scheme in our community.
Your web site offered us with valuable information to work on.

You’ve done a formidable activity and our whole neighborhood will
likely be thankful to you.

March 25th, 2014 at 19:50
modern furniture stores online disse:

It is the best time to make a few plans foor the long run and it’s time too bbe happy.
I have learn this subgmit and if I may just I wish to counsel you
some fascdinating things or tips. Perhaps you could write next articles rergarding this article.
I wish to read even more issues approximately it!

April 23rd, 2014 at 10:05
http://www.muvix.trend.in/ disse:

Howdy! Someone in my Myspace group shared this site with us so I came to check it out.
I’m definitely enjoying the information. I’m bookmarking and
will be tweeting this to my followers! Excellent blog and terrific design.

May 5th, 2014 at 9:38
august 1 birthstone disse:

Hey there! Someone in my Facebook group shared this website with
us so I came to check it out. I’m definitely loving the information.
I’m bookmarking and will be tweeting this to my
followers! Superb blog and superb design.

May 21st, 2014 at 7:36
7 ( disse:

I’m not that much of a internet reader to be honest but your blogs really nice, keep it up!
I’ll go ahead and bookmark your website to come back
later. Many thanks

June 14th, 2014 at 20:34
hacia comprar cosméticos por internet disse:

Whoa ! Este blog se ve exactamente justo como mi viejo!
Es en un completamente tema pero tiene más o menos la misma diseño de la página y el diseño.
Superb elección de los colores !

June 14th, 2014 at 22:54
anchor disse:

I go to see every day some websites and websites to read posts, but this blog gives quality
based articles.

June 15th, 2014 at 1:29
hasta unos fotomurales disse:

Hola , ​​me gusta leer todos a través de su artículo
Poste article . I como quería para escribir un pequeño comentario para apoyarle.

June 15th, 2014 at 4:49
Mira disse:

Your way of describing the whole thing in this
article is in fact fastidious, all can effortlessly be aware of it, Thanks a lot.

June 15th, 2014 at 22:43
mrdennis.com Blog » Regenerating Tissue With “Oilpulling” disse:

[...] gastrointestinal Side Effects Of Oil Pulling system, along with the body, to clean and give tissues click in a variety of organs. In this way, the worries that infection sites on these organs [...]

June 17th, 2014 at 2:08
when do i Ovulate disse:

I do not even understand how I ended up right here, but I thought this put up used to be good.
I do not recognize who you’re however certainly
you are going to a famous blogger if you happen to aren’t already.

June 30th, 2014 at 22:12
http://ovulationcycleguide.com disse:

Hello there! This is kind of off topic but I need some advice from an established blog.
Is it difficult to set up your own blog? I’m not very techincal but I can figure things out
pretty fast. I’m thinking about making my own but I’m not sure where to begin. Do you have any tips or suggestions?

July 4th, 2014 at 22:14
Francine disse:

Hey I know this is off topic but I was wondering if you knew of any widgets
I could add to my blog that automatically tweet my newest twitter updates.
I’ve been looking for a plug-in like this for quite some time
and was hoping maybe you would have some experience with something like this.
Please let me know if you run into anything. I truly enjoy reading your blog and I
look forward to your new updates.

July 22nd, 2014 at 15:58
Candra disse:

Hey There. I found your blog using msn. That is
an extremely well written article. I will make sure to bookmark it and come back to learn more of your useful
info. Thanks for the post. I will certainly comeback.

Deixe um comentário