arduino库文件建立方法.docx

上传人:b****4 文档编号:24261699 上传时间:2023-05-25 格式:DOCX 页数:8 大小:17.78KB
下载 相关 举报
arduino库文件建立方法.docx_第1页
第1页 / 共8页
arduino库文件建立方法.docx_第2页
第2页 / 共8页
arduino库文件建立方法.docx_第3页
第3页 / 共8页
arduino库文件建立方法.docx_第4页
第4页 / 共8页
arduino库文件建立方法.docx_第5页
第5页 / 共8页
点击查看更多>>
下载资源
资源描述

arduino库文件建立方法.docx

《arduino库文件建立方法.docx》由会员分享,可在线阅读,更多相关《arduino库文件建立方法.docx(8页珍藏版)》请在冰豆网上搜索。

arduino库文件建立方法.docx

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > PPT模板 > 自然景观

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1