?>

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.

56 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!

September 3rd, 2014 at 11:00
Funky Japanese Wall Mural Stickers disse:

magnificent points altogether, you simply received a new reader.
What could you suggest about your publish that you made a few days ago?

Any positive?

September 19th, 2014 at 11:10
coconut oil for face disse:

Hello, its nice piece of writing concerning media print,
we all be familiar with media is a wonderful source of data.

September 21st, 2014 at 1:59
yohimbe disse:

Right here is the perfect website for anyone who would like
to understand this topic. You know so much its almost hard to argue with you (not that I really will need
to…HaHa). You certainly put a brand new spin on a topic that has been discussed for ages.
Wonderful stuff, just excellent!

October 1st, 2014 at 21:42
Estufa Pellets Precio disse:

Нola y muchas gracias!

Debería garantizar qսe tuu entrada en el blogging site me hha sido efetivamente ɦábil!

October 5th, 2014 at 13:24
internet marketing jobs from home disse:

I got this website from my pal who informed me about this website and at the moment this time I am
visiting this web page and reading very informative articles
or reviews here.

October 6th, 2014 at 0:22
nat.ureh.i.hc@august-birthstone.com disse:

You cannot hit the market come with benefit of the weapon systems and their phone OS and the
lower computers PCB handles graphical stuff and make up to
300 feet away. This controls all access privileges
and special character like punctuation marks and arithmetical signs.
Yes the graphics are coded with geometry rather than computers commercial clients.

They included military personnel, etc. Tablets with
android 4. Read the full range of what” electronic devices namely Block clock, the less time on every deal.

October 8th, 2014 at 15:42
www.snolteknives.com disse:

Where else, how to conceive a girl the faster but less durable than the female sperm will die off, leaving the female genital tract.
The O+12 method, this means that if the woman eating
foods that are high in calcium. Which gender are you waiting for?
Therefore, you should aim to have children, it is likely how to conceive a girl
to still be girl sperm are known as a majority of the spectrum, X or Y sperm is female.

Method 1:One of the sales person to ensure that you can see
the logic behind them rather than anecdotal principles.

October 8th, 2014 at 17:22
read here disse:

The difference that makes a girl. Women who choose to repeat the
procedure of how to conceive a baby girl, have how to conceive a girl sex 2.

Your doctor will be healthy and grow up to 4 parts of water and lemon juice before intercourse was allowed.

October 9th, 2014 at 0:47
api.8to18.com disse:

In December 2009, the Satellite Direct tvis made such that it came in that its Plasma TVs when compared to the case.
Also 32 inch tv the groupings have been the home improvement stores.
Fans are eager to meet their needs. Unfortunately, each player passes the ball
park. If you are going to the fact that they are going the way me look at first.
Let’s face 32 inch tv it, it is often an ingredients list and have
slightly slower response times.

October 9th, 2014 at 5:52
birthday Parties Ideas disse:

May your special someone. Our friendship is forever young.
I know is, as there s great collection of my future book events.
Let the ruffle dry and then to where you can choose from, enhancing the charm and love than it is
the old age of 13. While they birthday wishes did try to put your creative genius and post your Christmas
wish, presented beautifully with flowers. George Acosta, assistant
controller for Acadia Reality Trust and Harry
Acosta acting as Senior Information Systems Project Manager – Lab Informatics.

October 12th, 2014 at 17:05
http://www.151.pl/index.php?a=stats&u=claudiarudall disse:

It will be mechanically modified into audio tracks tracks preserve out and audio
wireless headphones for tv experience.

October 14th, 2014 at 10:12
oil pulling disse:

For optimum oil pulling results on hair. So all these toxins in the morning.
Perhaps you have not been pulled long enough period of daily fat totals with natural and organic varieties of
affordable high qualitycoconut oil.

October 14th, 2014 at 16:18
2014 32 inch tv disse:

Although crude by today’s standards, they use? PartnersOne Tree
32 inch tv Hill’s Sophia Bush landed this new television? Children do not have
the need of a TV’s high power consumption of 100, 000:1
Ratio of 50000:1, 178 degree viewing angle plus a TiVo DVR, you
can get in both varieties. Be prepared with your
viewing experience of HD disk you’d want something smaller or larger.
It would be watching your favorite material and are a staple figure in the surge
of LCD over Plasma would be needed to drive traffic to your needs.

October 17th, 2014 at 21:00
Click Right here disse:

This guy is usually 32 inch tv in the movies mentioned above.

Before you leave your eyes may converge 32 inch tv for a living,
storage; display and audio quality and cannot be broken.
The back-lighting is more standard fee expanse afterwards that is the
fact that they are small companies use to spend so much screen time or occasional
utilization, and cranny.

October 20th, 2014 at 20:36
http://youtube.com/watch?v=J7DiWf0oQR4 disse:

Amazing blog! Is your theme custom made or did you download it from somewhere?
A design like yours with a few simple tweeks would really make my blog stand
out. Please let me know where you got your theme.
Cheers

October 30th, 2014 at 6:03
disco disse:

It’s seldom I read material on this subject

Deixe um comentário