arduino库文件建立方法.docx
《arduino库文件建立方法.docx》由会员分享,可在线阅读,更多相关《arduino库文件建立方法.docx(8页珍藏版)》请在冰豆网上搜索。
arduino库文件建立方法
WritingaLibraryforArduino
ThisdocumentexplainshowtocreatealibraryforArduino.ItstartswithasketchforflashingMorsecodeandexplainshowtoconvertitsfunctionsintoalibrary.Thisallowsotherpeopletoeasilyusethecodethatyou'vewrittenandtoeasilyupdateitasyouimprovethelibrary.
Formoreinformation,seethe APIStyleGuide forinformationonmakingagoodArduino-styleAPIforyourlibrary.
WestartwithasketchthatdoessimpleMorsecode:
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);
}
[GetCode]
Ifyourunthissketch,itwillflashoutthecodeforSOS(adistresscall)onpin13.
Thesketchhasafewdifferentpartsthatwe'llneedtobringintoourlibrary.First,ofcourse,wehavethe dot() anddash() functionsthatdotheactualblinking.Second,there'sthe ledPin variablewhichthefunctionsusetodeterminewhichpintouse.Finally,there'sthecallto pinMode() thatinitializesthepinasanoutput.
Let'sstartturningthesketchintoalibrary!
Youneedatleasttwofilesforalibrary:
aheaderfile(w/theextension.h)andthesourcefile(w/extension.cpp).Theheaderfilehasdefinitionsforthelibrary:
basicallyalistingofeverythingthat'sinside;whilethesourcefilehastheactualcode.We'llcallourlibrary"Morse",soourheaderfilewillbeMorse.h.Let'stakealookatwhatgoesinit.Itmightseemabitstrangeatfirst,butitwillmakemoresenseonceyouseethesourcefilethatgoeswithit.
Thecoreoftheheaderfileconsistsofalineforeachfunctioninthelibrary,wrappedupinaclassalongwithanyvariablesyouneed:
class Morse
{
public:
Morse(int pin);
void dot();
void dash();
private:
int _pin;
};
[GetCode]
Aclassissimplyacollectionoffunctionsandvariablesthatareallkepttogetherinoneplace.Thesefunctionsandvariablescanbe public,meaningthattheycanbeaccessedbypeopleusingyourlibrary,or private,meaningtheycanonlybeaccessedfromwithintheclassitself.Eachclasshasaspecialfunctionknownasa constructor,whichisusedtocreatean instance oftheclass.Theconstructorhasthesamenameastheclass,andnoreturntype.
Youneedacoupleofotherthingsintheheaderfile.Oneisan#includestatementthatgivesyouaccesstothestandardtypesandconstantsoftheArduinolanguage(thisisautomaticallyaddedtonormalsketches,butnottolibraries).Itlookslikethis(andgoesabovetheclassdefinitiongivenpreviously):
#include"Arduino.h"
[GetCode]
Finally,it'scommontowrapthewholeheaderfileupinaweirdlookingconstruct:
#ifndefMorse_h
#defineMorse_h
//the#includestatmentandcodegohere...
#endif
[GetCode]
Basically,thispreventsproblemsifsomeoneaccidently#include'syourlibrarytwice.
Finally,youusuallyputacommentatthetopofthelibrarywithitsname,ashortdescriptionofwhatitdoes,whowroteit,thedate,andthelicense.
Let'stakealookatthecompleteheaderfile:
/*
Morse.h-LibraryforflashingMorsecode.
CreatedbyDavidA.Mellis,November2,2007.
Releasedintothepublicdomain.
*/
#ifndefMorse_h
#defineMorse_h
#include"Arduino.h"
class Morse
{
public:
Morse(int pin);
void dot();
void dash();
private:
int _pin;
};
#endif
[GetCode]
Nowlet'sgothroughthevariouspartsofthesourcefile,Morse.cpp.
Firstcomesacoupleof#includestatements.ThesegivetherestofthecodeaccesstothestandardArduinofunctions,andtothedefinitionsinyourheaderfile:
#include"Arduino.h"
#include"Morse.h"
[GetCode]
Thencomestheconstructor.Again,thisexplainswhatshouldhappenwhensomeonecreatesaninstanceofyourclass.Inthiscase,theuserspecifieswhichpintheywouldliketouse.Weconfigurethepinasanoutputsaveitintoaprivatevariableforuseintheotherfunctions:
Morse:
:
Morse(int pin)
{
pinMode(pin, OUTPUT);
_pin = pin;
}
[GetCode]
Thereareacoupleofstrangethingsinthiscode.Firstisthe Morse:
:
beforethenameofthefunction.Thissaysthatthefunctionispartofthe Morse class.You'llseethisagainintheotherfunctionsintheclass.Thesecondunusualthingistheunderscoreinthenameofourprivatevariable, _pin.Thisvariablecanactuallyhaveanynameyouwant,aslongasitmatchesthedefinitionintheheaderfile.Addinganunderscoretothestartofthenameisacommonconventiontomakeitclearwhichvariablesareprivate,andalsotodistinguishthenamefromthatoftheargumenttothefunction(pin inthiscase).
Nextcomestheactualcodefromthesketchthatyou'returningintoalibrary(finally!
).Itlooksprettymuchthesame,exceptwith Morse:
:
infrontofthenamesofthefunctions,and _pin insteadof 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);
}
[GetCode]
Finally,it'stypicaltoincludethecommentheaderatthetopofthesourcefileaswell.Let'sseethewholething:
/*
Morse.cpp-LibraryforflashingMorsecode.
CreatedbyDavidA.Mellis,November2,2007.
Releasedintothepublicdomain.
*/
#include"Arduino.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);
}
[GetCode]
Andthat'sallyouneed(there'ssomeotherniceoptionalstuff,butwe'lltalkaboutthatlater).Let'sseehowyouusethelibrary.
First,makea Morse directoryinsideofthe libraries sub-directoryofyoursketchbookdirectory.CopyormovetheMorse.handMorse.cppfilesintothatdirectory.NowlaunchtheArduinoenvironment.Ifyouopenthe Sketch>ImportLibrary menu,youshouldseeMorseinside.Thelibrarywillbecompiledwithsketchesthatuseit.Ifthelibrarydoesn'tseemtobuild,makesurethatthefilesreallyendin.cppand.h(withnoextra.pdeor.txtextension,forexample).
Let'sseehowwecanreplicateouroldSOSsketchusingthenewlibrary:
#include
Morsemorse(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);
}
[GetCode]
Thereareafewdifferencesfromtheoldsketch(besidesthefactthatsomeofthecodehasmovedtoalibrary).
First,we'veaddedan#includestatementtothetopofthesketch.ThismakestheMorselibraryavailabletothesketchandincludesitinthecodesenttotheboard.Thatmeansifyounolongerneedalibraryinasketch,youshoulddeletethe#includestatementtosavespace.
Second,wenowcreateaninstanceoftheMorseclasscalled morse:
Morsemorse(13);
[GetCode]
Whenthislinegetsexecuted(whichactuallyhappensevenbeforethe setup() function),theconstructorfortheMorseclasswillbecalled,andpassedtheargumentyou'vegivenhere(inthiscase,just 13).
Noticethatour setup() isnowempty;that'sbecausethecallto pinMode() happensinsidethelibrary(whentheinstanceisconstructed).
Finally,tocallthe dot() and dash() functions,weneedtoprefixthemwith morse. -thenameoftheinstancewewanttouse.WecouldhavemultipleinstancesoftheMorseclass,eachontheirownpinstoredinthe_pinprivatevariableofthatinstance.Bycallingafunctiononaparticularinstance,wespecifywhichinstance'svariablesshouldbeusedduringthatcalltoafunction.Thatis,ifwehadboth:
Morsemorse(13);
Morsemorse2(12);
[GetCode]
theninsideacallto morse2.dot(), _pin wouldbe12.
Ifyoutriedthenewsketch,youprobablynoticedthatnothingfromourlibrarywasrecognizedbytheenvironmentandhighlightedincolor.Unfortunately,theArduinosoftwarecan'tautomaticallyfigureoutwhatyou'vedefineinyourlibrary(thoughitwouldbeanicefeaturetohave),soyouhavetogiveitalittlehelp.Todothis,createafilecalledkeywords.txt intheMorsedirectory.Itshouldlooklikethis:
Morse KEYWORD1
dash KEYWORD2
dot KEYWORD2
[GetCode]
Eachlinehasthenameofthekeyword,followedbyatab(notspaces),followedbythekindofkeyword.Classesshouldbe KEYWORD1 andarecoloredorange;functionsshouldbe KEYWORD2 andwillbebrown.You'llhavetorestarttheArduinoenvironmenttogetittorecognizethenewkeywords.
It'salsonicetoprovidepeoplewithanexamplesketchthatusesyourlibrary.Todothis,createan examples directoryinsidethe Morse directory.Then,moveorcopythedirectorycontainingthesketch(let'scallit SOS)wewroteaboveintotheexamplesdirectory.(Youcanfindthesketchusingthe Sketch>ShowSketchFolder command.)IfyourestarttheArduinoenvironment(thisisthelasttime,Ipromise)-you'llseea Library-Morse iteminsidethe File>Sketchbook>Examples menucontainingyourexample.Youmightwanttoaddsomecommentsthatbetterexplainhowtouseyourlibrary.
Ifyou'dliketocheckoutthecompletelibrary(withkeywordsandexample),youcandownloadit:
Morse.zip.
That'sallfornowbutI'llprobablywriteanadvancedlibrarytutorialsoon.Inthemeantime,ifyouhaveanyproblemsorsuggestions,pleas