Anda di halaman 1dari 9

201761 [Tutorial]ArduinoTimerAgendamentoderetornodechamadaRhesoft

Tempo de leitura ~ 2 minutos


Siga-me | @ Aron-bordin

[Tutorial] Arduino Timer - Agendando callbacks

Bem vinda!!

publicao, vou apresentar- lhe o mdulo Arduino Timer do .PNG Arduino Framework. Este mdulo permite agendar uma chamada de funo
Nesta
no futuro; Uma vez ou repetidamente em intervalos especi cados. Isso torna seu cdigo mais uido, evitando atraso () e consumindo menos energia.

Vamos dar uma olhada!!

Sobre a .PNG Arduino Framework

O .PNG Arduino Framework foi desenvolvido por estudantes da Unesp - Universidade Estadual de So Paulo, com o objetivo de facilitar o
desenvolvimento do projeto Arduino. A estrutura possui uma cadeia de classes modulares, compatvel com alguns componentes Arduino.

Cdigo fonte

Receba atualizaes Follow @aronbordin

Estrela: Star 10

Contribuir: Fork 12

Download: Download

Como usar Timer no Arduino

Leia os documentos para obter mais informaes sobre isso: http://png-arduino-framework.readthedocs.org/timer.html

A partir de agora, voc pode abrir o seu Arduino IDE , File -> Examples -> Arduino Timer . D uma olhada no exemplo e teste se tudo est funcionando.

A primeira coisa incluir a lib no seu esboo e criar um ponteiro do tipo Timer . Com este temporizador, Arduino poder agendar uma funo de
retorno de chamada no intervalo con gurado.

http://blog.rhesoft.com/2014/06/18/tutorialusingtimerobjectintervalandsingleshotcallbackinarduino/ 1/9
201761 [Tutorial]ArduinoTimerAgendamentoderetornodechamadaRhesoft

#include"Timer.h"
Timer*timer1=newTimer(500);//willcallthecallbackintheintervalof500ms Siga-me | @ Aron-bordin

Na sua seput () , adicione-o:

voidsetup(){
Serial.begin(9600);
timer1>setOnTimer(&PrintHello);//callbackfunction
timer1>Start();//startthethread.
}

Agora declare a funo PrintHello:


voidPrintHello(){
Serial.println("Hellotimer!!");
}


E, para manter seu temporizador em execuo, on loop () add:

voidloop(){
timer1>Update();
}

Com este cdigo, o Arduino ser executado e veri car se o Timer Object est pronto para chamar a funo de retorno de chamada. Se assim for, a
funo ser chamada e ser impressa no Serial.

[Importante] Voc no deve usar o comando delay (), ou Timer no funcionar! D uma olhada no prximo tpico e veja como substituir o atraso () com
este lib.

Replace Arduino delay () com Timer

O temporizador funciona como um atraso (), voc pode "esperar" at chamar algo.

Exemplo1 - Usando delay ():

voidloop(){
Serial.println("Usingdelay()
delay(500);
}

Exemplo2 - Substituio de atraso () com Arduino Timer:

Timer*timer=newTimer(500);
timer>setOnTimer(&Hello);

voidHello(){
Serial.println("UsingTimer!!:)");
}

voidloop(){
timer>Update();
}

Os dois cdigos funcionam da mesma forma, aguardaro 500 ms e mostraro uma mensagem. Mas quando voc usa o Temporizador, seu programa
estar sempre em execuo, ento, se voc precisar chamar um sensor em um intervalo, voc pode us-lo facilmente. Voc pode criar tantos
temporizadores quanto necessrio, e veri car cada sensor, ou chamar cada funo quando voc precisar.

isso mesmo, se voc tiver algum problema, precisa de ajuda, sugesto ou esse tipo de coisa, apenas comente aqui!

Obrigado por ler, vejo voc na prxima postagem.

http://blog.rhesoft.com/2014/06/18/tutorialusingtimerobjectintervalandsingleshotcallbackinarduino/ 2/9
201761 [Tutorial]ArduinoTimerAgendamentoderetornodechamadaRhesoft

Siga-me | @ Aron-bordin

TESTE GRTIS


ARDUINO CALLBACK CPP COMO IDE INTERVALO DE OBJETO DE PROGRAMAO FIO TEMPORIZADOR TIMEROBJECT TUTORIAL UNO

BY ARON BORDIN

GOSTAR TWEET +1


Sobre o autor

Aron Bordin

Estudante de Cincia da Computao e pesquisador de AI. Sempre codi cando algo divertido :)

Follow @aronbordin

37Comments RhesoftBlog
1 Login

SortbyBest
Recommend Share

Jointhediscussion

Tomayearago
Hello,

IcameacrossthislibrarywhichIcansavemealotoftimeonaprojectbutIsomequestions:
1)YoumentionedthatyouchangedfromTimerObject.htoTimer.hwhat'sthedifference,istherebugfixes?
2)I'mtryingtotogglethreerelay'son/off8timesatdifferenttimeswithin15minuteswhichseemspossiblebutisthereanywayofhavingadjustable
timewithprogramoramIlockedintoeachObjectinthebeginning?
Thanks,Tom
Reply Share

AronBordin Mod >Tom ayearago

Hi,
I'mnotsurerightnow,butIthinkthatIjustrenamedit.
YoucanchangethetimewithyourObj>setInterval(unsignedlongintms)anytime
Reply Share

Tom>AronBordinayearago
Wouldyouhaveasimpleexampleinusingtimer>setInterval()?Iwouldliketoturnon/offrelay3timesat(500)withinoneFunction
additionallyuseitforcount/timer.Also,I'vebeenusingthislibrarywithinanotherlibraryCountimer.hwhichseemstoworkwithoutany
problemspresently.
Thanksforthereplyandyourtime
http://blog.rhesoft.com/2014/06/18/tutorialusingtimerobjectintervalandsingleshotcallbackinarduino/ 3/9
201761 [Tutorial]ArduinoTimerAgendamentoderetornodechamadaRhesoft

Reply Share
Siga-me | @ Aron-bordin
AronBordin Mod >Tom ayearago

I'mwithnoarduinototestrightnow...Doyouhaveanysimplecodetoshare?(easierforme)
Butaboutyourquestion:whendoyouwanttochangethetimerinterval?
Reply Share

Tom>AronBordinayearago
Somethinglikethiswithinone"function"andnotcallingotherfunctions.

voidRepeat()
{
StringStr="AIRCYCLE"
genie.WriteStr(1,Str)
for(inti=0i<3i++)
{
digitalWrite(Relay1Pin,LOW)
delay(500)
digitalWrite(Relay1Pin,HIGH)
delay(500)
}
}
Also,Ihaveonecounter"refreshClock()"andwouldlikehaveasecondusingyourtimerunder"refreshClock2".Themillis
seemsnottoworkbecausewhencallitthestarttimeisnotzero.

voidrefreshClock()
seemore

Reply Share

Tom>Tomayearago
PertainingtocountingIhaveanoveralltimefortheprocessandnowIwouldliketohaveanfunctiontimeforwhenIcalltoturnon
arelay.Callrelayto'turnon"for45secwhichwouldbeviewedonadifferentoutputdisplaywhentheoverallcounterdisplay
wouldpauseuntilrelay"turnsoff"....kindofatoggle.
Reply Share

khairul2yearsago
Hi,
iwantdotheprojectthatwillbecontroltheservomotorusingArduino.theservomotormustbeswitchOnin10minutesandSwitchOFF3minutesand
continueswitchON10minuteagain.soimustneedaddsomecircuitconnecttoarduinoorijustdotheprogramming.Anyonecanhelpme?
Reply Share

Andrei2yearsago
Backwithaquestion...howdoesusingdelayinfluencestimerobject?
Scenario...myalgorithmdoessomefunctionseverysecond,anotheratfivesecondsandsomethingat10seconds.IfIinsertadelayinoneofthe
functionthatexecuteseveryfiveseconds,whatcouldhappen?Myguessisthatit'spossiblethatmyloopskipstheexecutionofoneoftheintervals
(one,fiveor10seconds).AmIright?
Reply Share

aronbordin>Andrei2yearsago
Whileinadelayit'snotpossibletocheckhowmanysecondshaspassed.It'llnotskiptheexecutionoftheinterval,butwillpostponeit.

Forexample,yourtimers:
1second
5seconds
10seconds

Ifyouuseadelaywith15seconds,after15secondsallofyourtimerswillbecalled(becauseallofthemhasainterval>=15)

Ifyouuseadelaywith5seconds,youronesecondtimerwillbecalledeach5secondandtheothertimerscanbecalledeach5or10
seconds.
Reply Share

Anonymous2yearsago
Hello!!
I'vebeentryingtocreatethisroutineinwhichi'mcheckingalevelswitch.Ifireada1fromthelevelswitchiwanttomakesurethatisasteady1before
idosomething.Sowhatineedistomakesurethatduring5secondsigetacontinuous1(thatitdoesn'tjumpto0atanytime).Iwasdoingthisbutit
doesntwork:

#include"TimerObject.h"

TimerObject*timer1=newTimerObject(50000)
constlonginterval=5000

intlast_ls
intpin=A0
http://blog.rhesoft.com/2014/06/18/tutorialusingtimerobjectintervalandsingleshotcallbackinarduino/ 4/9
201761 [Tutorial]ArduinoTimerAgendamentoderetornodechamadaRhesoft
intpin=A0
intls
Siga-me | @ Aron-bordin
voidsetup(){
timer1>setOnTimer(&Salto)
Serial.begin(9600)
pinMode(pin,INPUT)
}
seemore

Reply Share

aronbordin>Anonymous2yearsago
I'mnotsureaboutwhatyouaretryingtodo,butprobablythisistheproblem,becausewhenyoucalltheStartfunction,it'llrestartthetime
counting.Ifyouneedtoturnthetimeroffandcontinueitlater,usetheStart()atsetup(),andthenusePause()andResume()toenableand
disableyourtimer.
Reply Share

yinita20052yearsago
HeyAron!
It'smeagain:(..Soihavebeenworkingwithyourcodeandicameacrossanotherchallenge.,iwilltrytoexplainitwiththiscode:

.
.
.
voidTimer2(){

turnV1on!
}
.
.
.
voidloop(){
.
.

timer2>Update()

seemore

Reply Share

yinita2005>yinita20052yearsago
Ifigureditout!!!LOL..ijustsetonemoreconditionandnowitsworking!!!iwillshareyoumywholecodeoneitsdone!
Reply Share

yinita20052yearsago
Thisiswhatimworkingon:

time0:
Process1//Goesonduring30minutes

if(Process1isdone)
Process2//Goesonduring2hours
if(Process2isdone)
Process3//Goesonduring6hours
.......

..

if(Finalprocessisdone)
GobacktoProcess1

Idontreallyknowhowtousethelibraryforthispurpose!!helppppp
Reply Share

aronbordin>yinita20052yearsago
Hi!

Checkthealgorithmtothisworkflow:
1)Turnvalv1on
2)Wait2hours
3)Turnvalv2on
4)Wait6hours
5)Turnvalv3on
6)Wait2minutes
7)Repeatprocessfrom17

Takealookinthisgist:https://gist.github.com/aro...
http://blog.rhesoft.com/2014/06/18/tutorialusingtimerobjectintervalandsingleshotcallbackinarduino/ 5/9
201761 [Tutorial]ArduinoTimerAgendamentoderetornodechamadaRhesoft
Takealookinthisgist:https://gist.github.com/aro...
Reply Share
Siga-me | @ Aron-bordin

yinita2005>aronbordin2yearsago
Thankyousomuch!!!!yesthat'sexactlywhatineeded!
Reply Share

yinita20052yearsago
Thankyou!ifiwanttoincorporateaRTCforthetiming,thatwouldbeawholedifferentstory?alsoineedtocontrolmorethat20valvesandreceiveat
least15signalsfromsensors.Whatwouldbethebesttoapproachthis?Idon'tthinkthathavingjustabunchofarduinosisthebestsolution.Iwas
readingabouttheAVR,doyouhaveanyideasonthis??

Thankyouu
Reply Share

aronbordin>yinita20052yearsago
You'llgetasimilarresultwithRTC.Ifyouareworkingwithalotofcomponents,takealookifthereisnoarduinothatcanbeused:
http://arduino.cc/en/Produc...
Ifthepinsarenotenough,maybeusingaavrcanbeeasierforyou.
Reply Share

yinita2005>aronbordin2yearsago

Thankyou!yesinfactArduinoDuehasone!..butthewaywearestillwaitingonyourexampleofTimeObjecthandlingsomeoutputs
andprocesses.!

Reply Share

yinita20052yearsago
Hello!sorryforaskingthismuch,iwaswonderingifitispossibletocountupto6hoursormorewiththistimers?
Reply Share

aronbordin>yinita20052yearsago
Ow,Ijustforgottocamehere,sorryforthelatereply.Thecodeabovecanbealittleconfusingbecausetheyareusingsomebinarylogic.Take
alookinthispage:
http://www.cprogramming.com....

Yep,thelibsupportsalotoftime:https://duckduckgo.com/?q=4...:)
Reply Share

Ginna2yearsago
Thankyou,
Imtryingtorecreatethiscodeusingyourlibrary:

voiduseInterrupt(booleanv){
if(v){
//Timer0isalreadyusedformillis()we'lljustinterruptsomewhere
//inthemiddleandcallthe"CompareA"functionabove
OCR0A=0xAF
TIMSK0|=_BV(OCIE0A)
}else{
//donotcalltheinterruptfunctionCOMPAanymore
TIMSK0&=~_BV(OCIE0A)
}
}

Butidon'treallyknowwhatitmeans,rightnowimtryingtogetthiscodetowork:https://github.com/adafruit...

inaGalileoBoard.Soitsbeeneasierbyusingyourcode.Butwhenigottothatpartofthecodewhenit"interrupts"igetlost.

Thankyou!
Reply Share

Ginna2yearsago
Hello!iwaswonderingificaninterruptthetimer??
Reply Share

aronbordin>Ginna2yearsago
Youcancalltimer>Stop()ortimer>Pause()ifyouneedtoresumeitlater.Toresumeapausedtimer,justcalltimer>Resume()
Reply Share

Ginna2yearsago
Yessoundsgood!Thankyouverymuch.
Reply Share

Ginna2yearsago
Hello!Imworkingonadesalinationplantandoneoftheprocessesislikethis:
http://blog.rhesoft.com/2014/06/18/tutorialusingtimerobjectintervalandsingleshotcallbackinarduino/ 6/9
201761 [Tutorial]ArduinoTimerAgendamentoderetornodechamadaRhesoft
Hello!Imworkingonadesalinationplantandoneoftheprocessesislikethis:

1)Turnvalv1on Siga-me | @ Aron-bordin


2)Wait2hours
3)Turnvalv2on
4)Wait6hours
5)Turnvalv3on
6)Wait2minutes
7)Repeatprocessfrom17

Anditgoesonandonaslongastheplantison.Doyouthinkicanusethislibraryforthatpurpose?Doyouhaveanysuggestions?

Thankyou!
Reply Share

aronbordin>Ginna2yearsago
Ownice,goodlucklearningArduino!
Idon'tknowwhenI'llreleaseit,butI'llposthereaframeworktohelpnewnonexperiencedArduinocoderstoworkwiththiskindofproject.Itwill
beanArduinoframeworkthathandlesomecomponentsandmakethedevelopmenteasier.

Ok,I'mwithnoArduinothisweek,I'llbebackhomeontheMonday,thenIcansendyouasimpleexample:)
Reply Share

aronbordin>Ginna2yearsago
HiGinna!

Yep,it'spossibletodothatwiththislibrary.Ibelievethatthebestwayisusingonlysingleshottimers,soyouenableonetimerforeach
process.
Ifyouneedanyhelp,Icansendyouasamplecodeshowinghowtocreatethisworkflow.

AronBordin.
Reply Share

Ginna>aronbordin2yearsago
Yespleasethatwouldbeawesome,thisismyfirstprojectwitharduinosoimprettymuchlost!
Reply Share

Andrei2yearsago
IstherealimitforTimerObjectvalue?Ihavetwoactionsthatshouldhappenatdifferentinterval(onethatprintstemperatureonLCDeverysecondand
theotherthatwritestemperatureinafileevery10minutes).
I'vesetonetimerat1000(onesecond)andtheotherat600000(10minutes).Thetimersetat10minutescallsthefunctionat10seconds.I'mmakinga
mistake?((600000/1000)/60)=10minutes?!

Thanks!
Reply Share

aronbordin>Andrei2yearsago
OW,Ifixeditandjustforgottoupdatethegithubcode,agahahahha.It'soknow,ckeckifit'sworking,ifyouhaveanyproblem,justletmeknow.
Reply Share

aronbordin>Andrei2yearsago
Ow,thankyouforthedetails.Itwasabug,Ifixeditandupdatedatgithub.

Thx!
Reply Share

Andrei>aronbordin2yearsago
I'musingthelibrarymarkedinyourgithubas"7monthsold".Didyouupdatedsomethingthere?Idon'tknowmuch(almostanything)
aboutgithubs,butlogicalthingwouldbefortheupdateddatetobealsochanged.

Thealmostnoobsarethankingyouforsharingknowledge:)
Reply Share

Rafi3yearsago
HiAron,

I'vejuststumbledonyourlibrary,anditseemstobeexactlywhatI'mlookingfor.Ihadsomequestions,andpleaseexcusemystupidity,butthisismy
firstArduinoproject.IwanttouseyourtimerlibraryforSingleShottimers,whichifIunderstandcorrectly,willonlyrunthecallbackonce.

Thefirstquestionisaboutdisplayingthecurrenttimewithinthetimerinterval.I'mnotsurewhichofthefunctionswoulddothis.Iassumeditwasthe"int
getInterval()"one,butI'mnotsurehowtousethat.

Mysecondquestionisaboutthe"isEnabled"functions.Iwillbepausingandresumingthetimersatwill,butIwanttomakesureIonlyresumeoneof
thetimers.IthoughtperhapsIcoulduseisEnabled()tocheckwhetheratimerhadfinishedornot.AmIcompletelymisunderstandingthatfunction?

Thirdandfinalquestion(sorry)ishowcanIdisplaythetimeat1secondintervalswithinloop(),sinceIcan'tusedelay()?I'malittleconfusedhowtodo
thiswhenIamalreadyrunningtwoothertimers.I'mguessingtwotimerscanrunatthesametime,buthowdoIlinkSerial.print()toonespecifictimer?

http://blog.rhesoft.com/2014/06/18/tutorialusingtimerobjectintervalandsingleshotcallbackinarduino/ 7/9
201761 [Tutorial]ArduinoTimerAgendamentoderetornodechamadaRhesoft

Ifyoudon'thavetimetorespondtoeverything,Icompletelyunderstand.Thanksforthelibrary!
Reply Share
Siga-me | @ Aron-bordin

aronbordin>Rafi2yearsago
Ow,reallysorry,Iwascompletelybusyandjustforgottofixit..NowIupdatedthelib,ifyoustillneedingit,it'soknow.
Reply Share

aronbordin>Rafi3yearsago
Hi!Feelfreetoask,it'snicebecauseIseehowtoimprovethedocumentationandthelibitself.

1)Nowit'snotpossibletoshowthecurrenttimeontheinterval.
2)YoucanusetheisEnabledtotestit.Itwillbetruewhilerunning,andfalseafterfinished.
3)Youcanuseasmanytimersasnecessary,justusenodelayinyourcode.Toprintsomethingat1secondinterval,createasimpletimer,with
1second,andascallback,runafunctionthatprinteverythingthatyouneed.Liketheexample,https://github.com/aronbor...,butyoucanmodify
thecallbackfunctiontoprintyourvariables.
I'llbeworkingintheitem1inthisweek,probablytonight,soI'llupdatethelibinmygithub.
Reply Share

Rafi>aronbordin3yearsago
Wow,Ireallyappreciateyougettingbacktome.ThankstoyouranswersI'venowgota"functional"programwrittenbasedonthislibrary,
butitisn'tworkingasIwouldexpect.Ihadafriendtestmyprogramontheirarduinojusttomakesureitwasn'tmyboardhavingan
issue.

Thisistheproject,https://github.com/RowiDont...,andthebiggestissueI'mhavingisthatmy90stimerdoesnotrunthatlong,butrather
finishesinaround20seconds.

Anyideas?
Reply Share

ALSOONRHESOFTBLOG

[Tutorial]DevelopingAndroidBackgroundServices [Tutorial]FlipboardBottomSheetonAndroidStudio
4commentsayearago 3comments2yearsago

AvatartimobarrettHowcomeyoudidn'tcreditthesourceofthecode?The AvatarAvnishSharmahowcanimakethesearchviewwidgetthatopensthe
exactsamecodeexists,asdevelopedbygoogle,in resultsongoogle?

[Tutorial]Node.jsWebkitDesktopappwithAngularJSATodo ContactMeRhesoft
List 1comment2yearsago
1comment2yearsago
AvatarMatheusLimaOiAronEuestoufazendooseuprojetomasestoucom
Avatarmosbyjoshnicetutorialthankyou,buticouldn'texecute`yonode dificuldadenapartedeprogramaoAndroid.
webkit`soi'vedownloadedthecodefromgithubandI

Subscribe d AddDisqustoyoursiteAddDisqusAdd Privacy

http://blog.rhesoft.com/2014/06/18/tutorialusingtimerobjectintervalandsingleshotcallbackinarduino/ 8/9
201761 [Tutorial]ArduinoTimerAgendamentoderetornodechamadaRhesoft

Siga-me | @ Aron-bordin


consulte Mais informao

[Tutorial] Desenvolvendo servios de fundo do Android
### Bem-vindo! Nesta publicao, vou mostrar-lhe como desenvolver servios em segundo plano no Android Studio. Veremos dois tipos de servios:
`Service` a ... ... Continue lendo

[Tutorial] Biblioteca de cones de material do Android


Publicado em 29 de dezembro de 2015

[Tutorial] Boto de Processo Android - Botes Animados no Android Studio


Publicado em 29 de dezembro de 2015

2016 Aron Bordin. Desenvolvido por Jekyll usando o tema Neo-HPSTR .

http://blog.rhesoft.com/2014/06/18/tutorialusingtimerobjectintervalandsingleshotcallbackinarduino/ 9/9