?>

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();
  delay(3000);
}

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

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

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
{
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;
};

#endif

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);
  delay(250);
  digitalWrite(_pin, LOW);
  delay(250);
}

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

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:

#include 

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

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.

40 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:

meqywbmcnijc

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

gawjhlxpblnp

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
protein.

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.
Cheers!

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?
Cheers

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.

July 22nd, 2014 at 20:54
Zella disse:

What’s up, its good post about media print, we all be familiar with media is a wonderful source
of facts.

July 28th, 2014 at 20:15
Roberto disse:

Hi to every , as I am genuinely eager of reading this webpage’s post to be updated daily.
It includes good information.

July 30th, 2014 at 4:25
move to hawaii for free disse:

For the reason that the admin of this web page is working, no doubt very soon it will be famous, due to its quality contents.

August 5th, 2014 at 2:35
skillroar.com disse:

My partner and I stumbled over here different web page and
thought I may as well check things out. I like what I see so now i am following you.

Look forward to exploring your web page repeatedly.

August 9th, 2014 at 0:36
Hallie disse:

First of all I want to say terrific blog! I had a quick
question that I’d like to ask if you do not mind. I was interested to know how you center yourself and clear your head prior to
writing. I’ve had a difficult time clearing my mind in getting my thoughts out.
I truly do take pleasure in writing however it just seems like the first 10 to 15 minutes are
usually wasted simply just trying to figure out how to begin.
Any suggestions or hints? Thanks!

August 14th, 2014 at 0:24
domain disse:

Quality articles is the important to be a focus
for the visitors to visit the website, that’s what
this web site is providing.

August 16th, 2014 at 23:39
http://Relacion.Mmmidia.biz/Index.php?dll=profile&sub=blogview&Item_id=22629&item2_id=106587 disse:

Oh my goodness! Awesome article dude! Many thanks, However I am encountering
problems with your RSS. I don’t know why I can’t join it.
Is there anybody having similar RSS issues? Anyone that knows the answer can you
kindly respond? Thanx!!

August 17th, 2014 at 0:43
company gifts singapore disse:

If some one needs to be updated with latest technologies then he must be visit this
web site and be up to date daily.

August 17th, 2014 at 9:35
Jonathan disse:

Good day! Do you use Twitter? I’d like to follow you if that would be okay.
I’m absolutely enjoying your blog and look forward to new
posts.

August 19th, 2014 at 14:16
Adrienne disse:

Really the only tattoos for men practical thing to do is get a shower curtain setHaving given you a
great deal of thinking to the interior of your bathroom or home.
There are traditional designs as well as the light level.
The sets are available in spectacular designs that can often be found on the market.

September 1st, 2014 at 14:20
Elmer disse:

I like the valuable info you provide in your articles.
I’ll bookmark your weblog and check again here regularly.

I’m quite certain I’ll learn lots of new stuff right here!
Best of luck for the next!

September 2nd, 2014 at 2:25
large wall disse:

Wow that was odd. I just wrote an really long comment but after I clicked submit my comment didn’t appear.

Grrrr… well I’m not writing all that over again. Anyways, just wanted
to say great blog!

Deixe um comentário