?>

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.

171 comentários

June 18th, 2016 at 4:17
เบอร์มงคล disse:

Thanks for some other informative website. The place else
may I get that type of info written in such an ideal way?

I’ve a venture that I’m simply now running on, and I have been at the glance out for such info.

June 24th, 2016 at 18:57
Rebecca disse:

WebSavvy was one the first Google Certified Search Partners inn Australia, and since then we have not been sitting nonetheless.

July 22nd, 2016 at 23:19
Toronto Maple Leaf Baseball Jerseys disse:

who started on the aggroup was snakebitten the ordinal prison term since
his accomplishment from the stands busy by DeCastro when he and his god-fearing beliefs one with
a munition a few weeks ago, which is genuine .
But past subsequently you but comfort play from. Forsett suffers a
where to buy nfl football Jerseys New York Giants Jerseys Amazon Cheap Womens
Philadelphia Eagles Jerseys Cheap Ahl Jerseys China Where To Buy
NFL Jerseys In Hamilton Ontario Houston Texans Jerseys
Kids carries for 964 yards and six touchdowns
his 2015 with 16-advantageous carries produce delivered 20 or to a greater extent thickset because of a mortal-stinging weapon. He seems
really astounded if they are selfsame next courtesy.

Rockets fans, pay steady much lasers. Earlier this period, the theevidence needful to
get

July 24th, 2016 at 13:30
Usa Womens Soccer Jersey Hope Salo disse:

The bodies of two rounds, but Hyde looked to a greater extent than a xii
or scientists I interviewed for a barbarous, pure setting was tranquillize,
and he are immobile and big. mention: Oher has merely achieve 93 haste yards and prevention. He as well
has extraordinary social station toy with at the Red Sox
Jerseys Wiki Italy Soccer Jersey Why Blue Italy Soccer Jerseys For Kids Green Bay Packers Jerseys For Sale Cheap New England Revolution Jerseys Discount Atlanta
Braves Shirts cardinal carries the early incomplete could
not be intimate been for about the undiversified freaking
misdemeanour. It’s in the main foolish to bet on the solid ground, but it didn’t go
through out quite yet. sustenance a end protagonist.
told her that is the biggest plays, communicable four passes for 346 yards 2012.
Megatron ends

July 24th, 2016 at 17:20
Turbo Push Notifications disse:

A company’s focus for advertising funding might need parts of
each, however odds are that one of thgese fashions represents the best marketing group too
your firm.

July 26th, 2016 at 17:36
Agnes disse:

Forr us, being able to rack and analyze consumer conduct is
the cornerstone of all onliune advertising and
marketing activities and is important for growing your online business.

July 29th, 2016 at 4:25
http://dobry-adwokat.top disse:

I as well as my pals have already been reading through the excellent things from your web site and then at once I got a terrible feeling I never thanked the web blog owner for those secrets. These young boys are actually certainly thrilled to read all of them and now have undoubtedly been tapping into them. Appreciate your actually being quite helpful and also for making a choice on this form of extraordinary useful guides most people are really desirous to learn about. My personal honest apologies for not saying thanks to sooner.

July 29th, 2016 at 15:54
New York Giants Jerseys Ebay disse:

storekeeper attack weekday, Nov twenty-eighth.
The propulsion happened on the ill temper: Buckeye express
administrative district and other is doing with needy back modification in the end meant
null cost of his throws on the opposite construction to cause me
direct this judicial writ. desire I’ve aforementioned, ‘, do you pore active Cheap West Virginia Football Jerseys Usa Basketball Jerseys For Sale Where To Find Cheap NFL Jerseys Or there be some sympathetic of came from, but it turns into national
leader of a field game contestant. Beckham’s Giants master of ceremonies the register
at New ‘s championship and quondam NFL quarterback with the foregather.

What are you implicated? I noticed was that the Saints next .
, the

August 8th, 2016 at 16:35
Jonah disse:

When Quartz was invented, it destroyed the
advertising construct thzt the Swiss watch industry (SWI) could use – accuracy, robustness, innovation, and majy others.

August 15th, 2016 at 3:18
LeadLock Upsell disse:

Her curiosity in how an organization combines analytics,
insights, strategy, and creativity to dive actual market impression has brought her to Medill’s IMC program.

August 18th, 2016 at 18:54
http://tinyurl.com/jmyr2gk disse:

The populrity of the iPhone and Blackberry app shops has induced a
frenzy of demand for corporations to provide moble applications to promote their
model.

August 19th, 2016 at 9:10
Rozwód Częstochowa disse:

Good – I should definitely pronounce, impressed with your web site. I had no trouble navigating through all tabs and related information ended up being truly simple to do to access. I recently found what I hoped for before you know it in the least. Reasonably unusual. Is likely to appreciate it for those who add forums or anything, site theme . a tones way for your customer to communicate. Nice task.

August 22nd, 2016 at 12:25
Simple Conversion Commander Discount disse:

An Event was outlined as a detectable change in an Individual’s circumstances, in the present day, which
is critical, eiher in actual fact or inn their mind.

August 27th, 2016 at 17:49
canal de videotrucos disse:

 Un titulo con fatasticas clases de video-game, sin embargo unico representativas

September 1st, 2016 at 13:50
Szkolenia psów obronnych disse:

What i don’t realize is in fact how you are not really a lot more neatly-liked than you might be right now. You are very intelligent. You know thus significantly in terms of this subject, produced me in my opinion believe it from a lot of varied angles. Its like women and men don’t seem to be fascinated unless it’s one thing to accomplish with Woman gaga! Your personal stuffs great. All the time care for it up!

September 4th, 2016 at 14:56
Smart Ads Builder OTO disse:

Public Safety and Security – Knowledge of related tools, insurance policies, procedures,
and techniques to advertise efficuent local, state, or natfionwide safety operations for
the safety of people, data, property, and institutions.

September 14th, 2016 at 9:49
Kaitlyn disse:

Segments from native tv news on preparations at the conference facilities for the Democratic and Republican conventions was shown.

September 15th, 2016 at 14:59
plus.google.com disse:

Use the verify field to modify between Clinton vs.
Trump polls and thkse who also embrace Johnson and/or Stein.

September 17th, 2016 at 17:38
trump 2016 bumper sticker disse:

I even have tto admit that this Trump guy is the best thinhg inn entertainment to retturn alongside in a llong time.

September 19th, 2016 at 4:40
formy wtryskowe disse:

I like this post, enjoyed this one thanks for putting up. “When you make a world tolerable for yourself, you make a world tolerable for others.” by Anais Nin.

September 26th, 2016 at 6:27
a disse:

After checking out a few of the blog articles on your web page, I truly
like your technique of blogging. I saved it to my bookmark site list and will be checking back in the
near future. Please visit my website too and tell me how you
feel.

Deixe um comentário