an event driven arduino 1.6.x

Upload: flavio-andrade

Post on 07-Jul-2018

217 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/18/2019 An Event Driven Arduino 1.6.x

    1/39

    i

    QP state machine frameworks for Arduino

    Copyright © 2002-2006, Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note Event-Driven Arduino™ (1.6.x)Programming with P™

    Document !evi"ion #$cto%er &'1

    Copyright © Quantum Leaps, LLC

    info$%uantum-!eapscomwwwstate-machinecom

    mailto:[email protected]://www.state-machine.com/mailto:[email protected]://www.state-machine.com/

  • 8/18/2019 An Event Driven Arduino 1.6.x

    2/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    a%le o* +ontent"

    1 ,ntroduction..................................................................................................................................................... 1

    && A'out Arduino( &&2 )#ent-dri#en programming with Arduino(2&* +he structure of the QPC e#ent-dri#en framework for Arduino(*

    & etting tarted................................................................................................................................................ 2& .oftware /nsta!!ation622 ui!ding and "unning the !inky )1amp!e from the Q ode!ing +oo!32* ui!ding and "unning the !inky )1amp!e from the Arduino /4) &&25 "unning the P)L/CA Crossing )1amp!e in the Q too!&*27 +he 4ining Phi!osophers Pro'!em )1amp!e with the Preempti#e Q8 8erne!&726 odifying the )1amp!es to "educe Power Consumption &6

    / he tructure o* an Arduino 0etch *or P..................................................................................................1*& +he setup9: function &;

    *2 +he App!ication /nterface 9)#ents and .igna!s: &3** +he .tate achines 2&

    2 3oard upport Pac0age (3P) *or Arduino™...............................................................................................&/5& .P /nitia!ionAssert9: 27

    P4+55 i%rar7 *or Arduino™........................................................................................................................&67& +he %p>porth =eader ?i!e 2672 +he %p>portcpp ?i!e 2;7* +he %epcpp , %fcpp, %kcpp, and %scpp ?i!es2@

    6 # ool" *or Arduino................................................................................................................................... .. &86& Configuring +he )n#ironment aria'!es *062 +he 'ui!d>a#rtc! ui!d .cript*&6* Bp!oading Code to Arduino *265 +he rm Bti!ity for C!eaning Bp the ui!d *2

    9"ing he Preemptive : :ernel..................................................................................................................//;& Configuring the QPC Li'rary to Bse Preempti#e Q8 8erne!*5;2 Changes to the .P for the Preempti#e Q8 8erne! 9dpp-%k )1amp!e:*7

    ; !elated Document" and !e*erence"............................................................................................................. /6

    8 +ontact ,n*ormation........................................................................................................................................ /

    i

    egal Di"claimer"

    /nformation in this document is 'e!ie#ed to 'e accurate and re!ia'!e =owe#er, Quantum Leaps does not gi#e anyrepresentations or warranties, e1pressed or imp!ied, as to the accuracy or comp!eteness of such information and sha!! ha#eno !ia'i!ity for the conse%uences of use of such information

    Quantum Leaps reser#es the right to make changes to information pu'!ished in this document, inc!uding without !imitationspecifications and product descriptions, at any time and without notice +his document supersedes and rep!aces a!!information supp!ied prior to the pu'!ication hereof

     A!! designated trademarks are the property of their respecti#e owners

  • 8/18/2019 An Event Driven Arduino 1.6.x

    3/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    1 ,ntroduction+his document descri'es how to app!y the event-driven programming paradigm with modern "tatemachine" to de#e!op software for Arduino( graphicall7 .pecifica!!y, you wi!! !earn how to 'ui!dresponsi#e, ro'ust, and power-efficient Arduino programs with the open source QP(C acti#e o'ectframework, which is !ike a modern real-time operating "7"tem 9"+D.: specifica!!y designed fore1ecuting e#ent-dri#en, encapsu!ated state machines 9acti#e o'ects:

    Eou wi!! a!so see how to take Arduino programming to the ne1t !e#e! 'y using the the free Q( mode!ing

    too! 

    to generate Arduino code automaticall7 from state diagrams +he Q mode!ing too! together withthe 'ui!d script pro#ided in the QP 4e#e!opment 8it 9Q48: for Arduino a!!ow you to 'ui!d and up!oad the Arduino sketches entire!y from the Q too! =owe#er, the pro#ided e1amp!es remain compati%le withthe "tandard Arduino ,DE

    1.1 A%out Arduino™

     Arduino( 9see wwwarduinocc: is an open-sourcee!ectronics prototyping p!atform, designed to makedigita! e!ectronics more accessi'!e to non-specia!istsin mu!tidiscip!inary proects +he hardware consists of a simp!e Arduino printed circuit 'oard with an Atme!

     A" microcontro!!er and standardi

  • 8/18/2019 An Event Driven Arduino 1.6.x

    4/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    1.& Event-driven programming with Arduino™

    +raditiona!!y, Arduino programs are written in a "e>uential mannerGhene#er an Arduino program needs to synchroni

  • 8/18/2019 An Event Driven Arduino 1.6.x

    5/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

     An e#ent-dri#en framework can 'e #ery simp!e /n fact, many proects in the Arduino P!ayground +utoria!s and "esources Protothreading, +iming N i!!is section pro#ide e1amp!es of rudimentary e#ent-dri#en frameworks +he genera! structure of a!! these rudimentary frameworks is shown in Listing 2

    +he framework in this case consists of the main Arduino !oop and the if statements that check for

    e#ents )#ents are effecti#e!y po!!ed during each pass through the main !oop, 'ut the main !oop does not get into tight po!!ing su'-!oops Ca!!s to functions that po!! interna!!y 9!ike delay(): are not a!!owed,'ecause they wou!d s!ow down the main !oop and defeat the main purpose of e#ent-dri#en programming9responsi#eness: +he app!ication in this case consists of a!! the e#ent hand!er functions9event&Handler(), event-Handler(), etc: Again, the critica! difference from se%uentia! programminghere is that the e#ent hand!er functions are not a!!owed to po!! for e#ents, 'ut must consist essentia!!y of!inear code that %uick!y return" contro! to the framework after hand!ing each e#ent

    +his arrangement a!!ows the e#ent-dri#en program to remain re"pon"ive to a!! e#ents a!! the time, 'ut it isa!so the 'iggest cha!!enge of the e#ent-dri#en programming sty!e, 'ecause the app!ication 9the e#enthand!er functions: must 'e designed such that for each new e#ent the corresponding e#ent hand!er canpick up where it !eft off for the !ast e#ent 9A se%uentia! program has much !ess of this pro'!em, 'ecause itcan hang on in tight po!!ing !oops around certain p!aces in the code and process the e#ents in theconte1ts ust fo!!owing the po!!ing !oops +his arrangement a!!ows a se%uentia! program to mo#e natura!!y

    from one e#ent to the ne1t:

    Bnfortunate!y, the ust descri'ed main cha!!enge of e#ent-dri#en programming often !eads to ?"paghetti@code +he e#ent hand!er functions start off pretty simp!e, 'ut then if.s and ele-s must 'e added insidethe hand!er functions to hand!e the context proper!y ?or e1amp!e, if you design a #ending machine, youcannot process the Idispense productJ 'utton-press e#ent unti! the fu!! payment has 'een co!!ected +hismeans that somewhere inside the dipeneProdu"tuttonPreHandler() function you need an if.statement that tests the payment status 'ased on some g!o'a! #aria'!e, which is set in the e#ent hand!erfunction for payment e#ents Con#erse!y, the payment status #aria'!e must 'e changed after dispensingthe product or you wi!! a!!ow dispensing products without co!!ecting su'se%uent payments =opefu!!y yousee how this design %uick!y !eads to do

  • 8/18/2019 An Event Driven Arduino 1.6.x

    6/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    not-empty %ueue After finding the %ueue, the schedu!er e1tracts the e#ent from the %ueue and sends it tothe state machine associated with this %ueue, which is ca!!ed dispatching  of an e#ent to the statemachine

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    7/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    & etting tarted+o focus the discussion, this App!ication ote uses the Arduino BD'oard 'ased on the Atme! Atmega*2@p microcontro!!er 9see ?igure *:

    +he e1amp!e code has 'een 'ui!t entire!y inside the # modeling tool9#ersion *21 or higher:, 'ut it uses the compi!er and !i'raries in thestandard Arduino 1.6.x 9the !atest as of this writing:, which is a#ai!a'!efor a free down!oad from the Arduino we'site

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    8/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    &.1 o*tware ,n"tallation

    QPC for Arduino is distri'uted in a sing!e /P archi#e 3p"pp.4ver&56arduino.4ver-57ip, where4ver&5 stands for #ersion of the QPC framework and 4ver-5 for the #ersion of the Arduino software9eg, &61:

    Eou need to un

  • 8/18/2019 An Event Driven Arduino 1.6.x

    9/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    Dnce you identify the .ketch'ook fo!der, you simp!y und0-ver1FGarduino-ver&F.ip archive *or Arduion 1..x

    48rduino6#9et"hboo95 . :our 8rduino #9et"hboo9 folder.do"/ . do"u%entation< .86vent.*riven68rduino.&>?pdf @ thi do"u%ent< .86*PPpdf @ *ining Philoopher Proble% e?a%ple appli"ation< .86PIA8pdf @ Pdetrian Ight ABtrolled (PIA8) "roing e?a%ple

    of /

    http://www.state-machine.com/arduinohttp://www.state-machine.com/arduino

  • 8/18/2019 An Event Driven Arduino 1.6.x

    10/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    <.e?a%ple6avr/< .blin9y/ @ Cery i%ple Dblin9yE e?a%ple< < .blin9y . Fhe 0 eion file for the lin9y proe"t< < .blin9y3% . Fhe 0 %odel of the lin9y appli"ation

    < .dpp639/ @ *PP.0 e?a%ple with pree%ptive 0 9ernel (#e"tion J)< < .dpp . Fhe 0 eion file for the *PP proe"t< < .dpp3% . Fhe 0 %odel of the *PP appli"ation< .peli"an/ @ Pdetrian Ight ABtrolled (PIA8) "roing e?a%ple< < .peli"an . Fhe 0 eion file for the PIA8 proe"t< < .peli"an3% . Fhe 0 %odel of the PAI8 "roing appli"ation<.librarie/< .3p6avr/ . 0P library for 8CR.baed 8rduino< < .3ep"pp . 0P/A "o%ponent platfor%.independent i%ple%entation< < .3f"pp . 01/A "o%ponent platfor%.independent i%ple%entation< < .39"pp . 0/A "o%ponent platfor%.independent i%ple%entation< < .3"pp . 0#/A "o%ponent platfor%.independent i%ple%entation

    < < .3p6port"pp . 0P/A port for 8rduino i%ple%entation< < .3p6porth . 0P/A port for 8rduino interfa"e<.tool/< ."ript/ . tool "ontributed 0uantu% eap< < .build6avrt"l @ Generi" FA "ript for building 8rduino/8CR 9et"he< < .upload6avrbat @ at"h file for uploading 9et"he to the 8rduino/8CR board< .hare/ . 1older for the FA interpreter< < .t"lKL/ . fa"ilitie for FA KL< < . < .util/ . tool "ontributed 0uantu% eap< < .ABP:IGt?t . ter% of "opying thi "ode< < .GP-FMF . GP verion - open our"e li"ene< < .FA6IA#FMF . i"ene for the FA interpreter

    < < ."pe?e @ Ao%%and.line utility for "opying file< < .r%e?e @ Ao%%and.line utility for re%oving file ("leanup)< < .t"lKLdll @ * for the FA interpreter< < .t"lpipKLdll @ * for the FA interpreter< < .t"lhKLe?e @ FA #hell to e?e"ute FA "ript< < .t"lhe?e @ FA #hell to e?e"ute FA "ript (alia)<.GPvNt?t . GO General Publi" i"ene verion N.0P.8rduino6GP6?"eptiont?t @ GPvN e?"eption for 8rduino.R8*t?t . R8* file with bai" intru"tion

    )ach QP e1amp!e for Arduino 9in the e?a%ple6avr fo!der: contains a Q mode!, which is a fi!e with the

    e1tension 3%, such as 4#9et"hboo95e?a%ple6avrblin9yblin9y!3% , see Listing *: +hesemode!s and the Q mode!ing too! take Arduino programming to the ne1t !e#e! /nstead of coding the statemachines 'y hand, you draw them with the free Q mode!ing too!, attach simp!e action code to statesand transitions, and you generate the comp!ete Arduino sketch automatica!!yR!itera!!y 'y a press of a'utton 9see ?igure 6:

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    11/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    &.& 3uilding and !unning the 3lin07 Example *rom the # #odeling ool

    +o 'ui!d the pro#ided !inky e1amp!e, change to the 48rduino6#9et"hboo95e?a%ple6avrblin9y directory, and dou'!e-c!ick on the blin9y3% mode! fi!e /f you insta!!ed Q correct!y, this wi!! open the!inky mode! in the Q too!, as shown in ?igure 6  Hou %uild and upload the P example" directl7

    *rom the # modeling tool, without the need to !aunch the standard Arduino /4)

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    12/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    =igure < Adu"ting the A!D9,N$GI$#E and A!D9,N$G:E+I3$$: environmentvaria%le" in the #anage External ool" dialog %ox

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    13/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    =igure ;< 9ploading the code to the Arduino %oard

    &./ 3uilding and !unning the 3lin07 Example *rom the Arduino ,DE

     As mentioned 'efore, the QP e1amp!es are sti!! compati'!e with the standard Arduino /4) ?or e1amp!e,to 'ui!d and run the !inky e1amp!e, you dou'!e-c!ick on the fi!e blin9yino to open the proect in the

     Arduino /4), as shown in ?igure 3

    11 of /

    Log window showing theoutput from a#rdude

    Bp!oad Codeutton 9?&0:

    http://www.state-machine.com/arduinohttp://www.state-machine.com/arduino

  • 8/18/2019 An Event Driven Arduino 1.6.x

    14/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    =igure 8< he 3lin07 example in the Arduino ,DE

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    15/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    &.2 !unning the PE,+AN +ro""ing Example in the # tool

    +he P)destrian L/ght CDtro!!ed 9P)L/CA: crossing e1amp!e is 'ui!t and up!oaded in the simi!ar way asthe !inky e1amp!e, e1cept you open the peli"an3% e1amp!e Q mode! !ocated in the directory48rduino6#9et"hboo95e?a%ple6avrpeli"an

    efore you can test the e1amp!e, you need to understand the how it is supposed to work .o, theP)L/CA crossing operates as fo!!ows +he crossing 9see ?igure &0: starts with cars ena'!ed 9green !ightfor cars: and pedestrians disa'!ed 9I4onMt Ga!kJ signa! for pedestrians: +o acti#ate the traffic !ight changea pedestrian must push the 'utton at the crossing, which generates the P)4.>GA/+/K e#ent /nresponse, oncoming cars get the ye!!ow !ight, which after a few seconds changes to red !ight e1t,pedestrians get the IGa!kJ signa!, which short!y thereafter changes to the f!ashing I4onMt Ga!kJ signa!

     After the I4ontM Ga!kJ signa! stops f!ashing, cars get the green !ight again After this cyc!e, the traffic !ightsdonMt respond to the P)4.>GA/+/K 'utton press immediate!y, a!though the 'utton Iremem'ersJ that ithas 'een pressed +he traffic !ight contro!!er a!ways gi#es the cars a minimum of se#era! seconds ofgreen !ight 'efore repeating the traffic !ight change cyc!e Dne additiona! feature is that at any time anoperator can take the P)L/CA crossing off!ine 9'y pro#iding the D?? e#ent: /n the Ioff!ineJ mode thecars get the f!ashing red !ight and the pedestrians get the f!ashing I4onMt Ga!kJ signa! At any time theoperator can turn the crossing 'ack on!ine 9'y pro#iding the D e#ent:

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    16/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    =igure 11< eraerm erial erminal with the output *rom the PE,+AN cro""ing

    12 of /

    .eria! +ermina!utton 9?&&:

    +era+erm .eria!+ermina! window

    http://www.state-machine.com/arduinohttp://www.state-machine.com/arduino

  • 8/18/2019 An Event Driven Arduino 1.6.x

    17/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    &. he Dining Philo"opher" Pro%lem Example with the Preemptive : :ernel.

    ?ina!!y, the e1amp!e code contains the 4ining Phi!osophers Pro'!em 94PP: e1amp!e, which demonstratesmuti!p!e state machines and the preemptive Q8 kerne! 9see a!so .ection ;: +his e1amp!e is !ocated inthe directory 48rduino6#9et"hboo95e?a%ple6avrdpp639

    +he c!assica! 4ining Phi!osopher Pro'!em 94PP: was posed and so!#ed origina!!y 'y )dsger 4iikstra inthe &3;0s and is specified as fo!!ows ?i#e phi!osophers are gathered around a ta'!e with a 'ig p!ate ofspaghetti in the midd!e 9see ?igure &2: etween each two phi!osophers is a fork +he spaghetti is sos!ippery that a phi!osopher needs two forks to eat it +he !ife of a phi!osopher consists of a!ternate periodsof thinking and eating Ghen a phi!osopher wants to eat, he tries to ac%uire forks /f successfu! inac%uiring forks, he eats for a whi!e, then puts down the forks and continues to think +he key issue is thata finite set of tasks 9phi!osophers: is sharing a finite set of resources 9forks:, and each resource can 'eused 'y on!y one task at a time

    =igure 1&< Dining Philo"opher" Pro%lem

    Eou 'ui!d and up!oad the 4PP-Q8 e1amp!e to the Arduino BD 'oard the same way as the P)L/CAe1amp!e Fust !ike in the P)L/CA e1amp!e, the Bser L)4 in 4PP-Q8 is rapid!y turned on and off in theid!e !oop, which appears as a constant g!ow to a human eye

    +o see the actua! output from the 4PP-Q8 e1amp!e, you need to open a erial erminal 'y pressing the.eria! +ermina! 'utton on the Q too!'ar 9see ?igure 6: ?or the Arduino BD 'oard, the .eria! +ermina!shou!d 'e configured to 11&'' %aud rate

    1 of /

    +era+erm .eria!+ermina! window

    http://www.state-machine.com/arduinohttp://www.state-machine.com/arduino

  • 8/18/2019 An Event Driven Arduino 1.6.x

    18/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    &.6 #odi*7ing the Example" to !educe Power +on"umption

     As mentioned in .ection &2, the QPC framework a!!ows you to take ad#antage of the ArduinoprocessorMs !ow-power s!eep mode, which is the on!y way to achie#e rea!!y !ow-power design othpro#ided e1amp!es can 'e #ery easi!y modified to switch to the s!eep mode when no e#ents are a#ai!a'!e

    /n fact, the code is a!ready pro#ided for you, so a!! you need to do is ust to ena'!e this code As shown inListing 3, you un-comment the definition of the #8C6PBR macro in the fi!e bp"pp 9oard .upportPackage:

     After you recompi!e the code and down!oad to Arduino, you wi!! see that the Bser L)4 is no !ongerg!owing Actua!!y, it is g!owing, 'ut on!y for a few microseconds out of e#ery &0 mi!!iseconds, so youcannot see it +his #ery !ow 'rightness of the Bser L)4 means that the Arduino ackground !oop uses#ery !itt!e power, yet the app!ication performs e1act!y as 'eforeS +he upcoming .ection 5& e1p!ains whate1act!y happens when you define the macro #8C6PBR in bp!"pp

    16 of /

    http://www.state-machine.com/arduinohttp://www.state-machine.com/arduino

  • 8/18/2019 An Event Driven Arduino 1.6.x

    19/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    / he tructure o* an Arduino 0etch *or P)#ery e#ent-dri#en Arduino sketch for QP consists of four rough groups setup, e#ents, acti#e o'ects,and 'oard support package 9.P: +ypica!!y, the main sketch f i!e 9the !ino fi!e: contains the Aruino

    etup() function .ince the e#ents are shared, they are defined in a header fi!e 9the !h fi!e: Acti#eo'ects are defined in source fi!es 9the !"pp fi!es:, one acti#e o'ect per fi!e +he fo!!owing sectionsdescri'e these e!ements in more detai!

    /.1 he setup! *unction

    Listing 5 shows an e1amp!e Arduino sketch for QP +his sketch defines on!y the etup() function +hee1p!anation section immediate!y fo!!owing the !isting high!ights the main points

    i"ting 2< 7pical Arduino "0etch *or P (*ile dpp.ino)

     #! $in%&ude '(rduino.)' ** don+t ,or-et to in%&ude

     (&) Sin"lude Q3p6porthQ (-) Sin"lude QdpphQ (N) Sin"lude QbphQ

      // o"al."ope obe"t ....................................................... (L) tati" 0vt "ont Tl6table0ueue#toU6PHIBV; (W) tati" 0vt "ont Tl6philo0ueue#toU6PHIBVU6PHIBV; (>) tati" 0#ub"rit l6ub"r#toU8M6PO6#IGV; (J) 016PBB6(Fablevt) l6%lPool#toU-T6PHIBV; // torage for %all event pool

      // (K) void etup() { (X) #P6init(); // initiali7e the #P

    (&$) 0122init(); // initiali7e the fra%ewor9 and the underlying RF 9ernel

      // initiali7e event pool(&&) 0122poolInit(l6%lPool#to' i7eof(l6%lPool#to)' i7eof(l6%lPool#toU$V));

    (&-) 0122pInit(l6ub"r#to' 06*I(l6ub"r#to)); // init publih.ub"ribe

      // tart the a"tive obe"t  uintK6t n;  for (n = $; n 4 6PHIB; n) {(&N) 8B6PhiloUnV.5tart((uintK6t)(n &)'  l6philo0ueue#toUnV' 06*I(l6philo0ueue#toUnV));  +

    (&L) 8B6Fable.5tart((uintK6t)(6PHIB &)'  l6table0ueue#to' 06*I(l6table0ueue#to));  +

    90: )ach sketch for must inc!ude the standard J (rduino.)' header fi!e +his is necessary to make thesketch compati'!e with the arduino%a9et"l 'ui!d script 9see a!so .ection TTT:

    9&: )ach sketch for QP imports the QP !i'rary port to Arduino 9the 43p6porth5 header fi!e:

    92: +he app!ication header fi!e 9dpph in this case: contains the definition of signa!s and e#ents for theapp!ication +his fi!e is shared among most fi!es in the sketch

    1 of /

    http://www.state-machine.com/arduinohttp://www.state-machine.com/arduino

  • 8/18/2019 An Event Driven Arduino 1.6.x

    20/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    9*: +he header fi!e 'sph contains the faci!ities pro#ided 'y the oard .upport Package +his fi!e is a!soshared among most fi!es in the sketch

    95-7: +he app!ication must pro#ide storage for e#ent %ueues of a!! acti#e o'ects used in the app!ication=ere the storage is pro#ided at compi!e time through the statica!!y a!!ocated arrays of immuta'!e

    9const: pointers to e#ents96: /f the app!ication uses the pu'!ish-su'scri'e e#ent de!i#ery mechanism supported 'y QP, the

    app!ication must pro#ide the storage for the su'scri'er !ists +he su'scri'er !ists remem'er whichacti#e o'ects ha#e su'scri'ed to which e#ents +he si

  • 8/18/2019 An Event Driven Arduino 1.6.x

    21/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    /.& he Application ,nter*ace (Event" and ignal")

     An event represents occurrence that is interesting to the system An e#ent consists of two parts +he partof the e#ent ca!!ed the "ignal con#eys the type of the occurrence 9what happened: ?or e1amp!e, in the4PP app!ication the 8F6#IG signa! represents the permission to eat to a Phi!osopher acti#e o'ect,

    whereas HO=GR:6#IG con#eys to the +a'!e acti#e o'ect that a Phi!osopher wants to eat An e#ent cana!so contain additiona! %uantitati#e information a'out the occurrence in the form of event parameter"?or e1amp!e, the HO=GR:6#IG signa! is accompanied 'y the num'er of the Phi!osopher /n QP e#entsare represented as instances of the 0vt c!ass pro#ided 'y the framework .pecifica!!y, the 0vt c!asscontains the mem'er sig, to represent the signa! of that e#ent )#ent parameters are added in thesu'c!asses of 0vt, that is c!asses that inherit from 0vt

    ecause e#ents are shared among most of the app!ication components, it is con#enient to dec!are themin a separate header fi!e 9eg, dpp!h for the 4PP app!ication: Listing 7 shows the interface for the 4PPapp!ication +he e1p!anation section immediate!y fo!!owing the !isting high!ights the main points

    i"ting < he application header *ile *or DPP (*ile dpp.))

     (&) usin- na/espa%e QP0//au%e the 0P na%epa"e for all file in thi appli"ation

     (-) enu% *PP#ignal { (N) 8F6#IG = 06O#R6#IG' // publihed by Fable to let a philoopher eat  *B6#IG' // publihed by Philoopher when done eating  FRI8F6#IG' // publihed by #P to ter%inate the appli"ation (L) 8M6PO6#IG' // the lat publihed ignal

      HOGR:6#IG' // poted fro% hungry Philoopher to Fable (W) 8M6#IG // the lat ignal  +;

     (>) tru"t Fablevt 2 publi" 0vt {

      uintK6t philou%; // philoopher nu%ber  +;

      enu% { 6PHIB = W +; // nu%ber of philoopher

    9&: +his directi#e esta'!ishes the defau!t namespace to 'e QP, meaning that a!! e!ements not %ua!ifiede1p!icit!y are assumed to come from the namespace QP

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    22/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    95: +he constant 8M6PO6#IG de!imits the pu'!ished signa!s from the rest Eou can sa#e some "A'y pro#iding a !ower !imit of pu'!ished signa!s to QP 98M6PO6#IG: rather than the ma1imum of a!!signa!s used in the app!ication

    97: +he !ast enumeration 8M6#IG indicates the ma1imum of a!! signa!s used in the app!ication

    96: +he structure Fablevt represents a c!ass of e#ents to con#ey the Phi!osopher num'er in thee#ent parameter Fablevt inherits 0vt and adds the philo=u% parameter to it

    9;-@: +hese g!o'a! pointers represent acti#e o'ects in the app!ication and are used for posting e#entsdirect!y to acti#e o'ects ecause the pointers can 'e initia!i

  • 8/18/2019 An Event Driven Arduino 1.6.x

    23/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    /./ he tate #achine"

    +he QP framework a!!ows you to work with the modern hierarchical state machines 9aka, BLstatecharts: ?or e1amp!e, ?igure &* shows the =. for the P)L/CA crossing

    =igure 1/< he hierarchical "tate machine o* the PE,+AN cro""ing

    &1 of /

    operationa!

    entry , CA".>")4O P)4.>4D6+>GAL8

    off!ine

    entry ,

    e1it ,

    cars)na'!ed

    e1it ,

    peds)na'!ed

    e1it ,

    carsKreenentry , CA".>K"))6

    e1it ,

    carsEe!!ow

    entry , CA".>E)LLDG

    e1it ,

    pedsGa!kentry , P)4.>GAL8

    e1it ,

    peds?!ash

    entry ,

    e1it ,

    carsKreen6oPed

    entry ,

    carsKreen/nt

    entry ,

    carsKreenPedGait

    entry ,

     ,

      me-Usu'scri'e9P)4.>GA/+/6K>./K:O

    D??

    P)4.>GA/+/6K

    +/2)DB+

    +/2)DB+

    P)4.>GA/+/6K

    +/2)DB+

    +/2)DB+

    +/2)DB+

    Vme-Um>f!ashCtr S 0W ,

      --me-Um>f!ashCtrOVe!seW

    V9me-Um>f!ashCtr &: 0W ,

     .P>signa!Peds9P)4.>4D6+>GAL8:O

    Ve!seW ,

      .P>signa!Peds9P)4.>LA68:O

    +/2)DB+ ,

      me-Um>f!ashCtr X &O V9me-Um>f!ashCtr &: 0W ,

    CA".>")4O P)4.>4D6+>GAL8O

    Ve!seW , CA".>LA68O P)4.>LA68O

    D6

    http://www.state-machine.com/arduinohttp://www.state-machine.com/arduino

  • 8/18/2019 An Event Driven Arduino 1.6.x

    24/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    +he 'iggest ad#antage of hierarchica! state machines 9=.s: compared to the traditiona! finite statemachines 9?.s: is that =.s remo#e the need for repetitions of actions and transitions that occur in thenon-hierarchica! state machines Githout this a'i!ity, the comp!e1ity of non-hierarchica! state machinesIe1p!odesJ e1ponentia!!y with the comp!e1ity of the mode!ed system, which renders the forma!ismimpractica! for rea!-!ife pro'!ems

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    25/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    2 3oard upport Pac0age (3P) *or Arduino™+he QP e1amp!e sketches 94PP and P)L/CA: contain the fi!e bp!"pp, which stands for oard.upport Package 9.P: +his .P contains a!! 'oard-re!ated code, which consists of the 'oard

    initia!iK and friend  +

    &/ of /

    http://www.state-machine.com/arduinohttp://www.state-machine.com/arduino

  • 8/18/2019 An Event Driven Arduino 1.6.x

    26/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    9&: +his .P uses +imer2 as the source of the periodic c!ock tick interrupt 9+imer& is a!ready used topro#ide the Arduino %illi() ser#ice:

    9*: +he output compare register 9DC"2A: is !oaded with the #a!ue that determines the !ength of thec!ock tick interrupt +his #a!ue, in turn, is determined 'y the #P6AIA#6PR6#A constant, which

    current!y is set to &00 times per second

    ?or each ena'!ed interrupt you need to pro#ide an /nterrupt .er#ice "outine 9/.": /."s are not theregu!ar C functions, 'ecause they need a specia! code to enter and e1it onethe!ess, the Arduinocompi!er 9GinA": supports writing /."s in C, 'ut you must inform the compi!er to generate thespecia! /." code 'y using the macro I#R() Listing @ .hown the system c!ock tick /." for Arduino

    i"ting ;< 7"tem cloc0 tic0 ,! *or Arduino (*ile sp.%pp)

     (&) I#R(FIR-6ABP86ve"t) {  // o need to "lear the interrupt our"e in"e the Fi%er- "o%pare  // interrupt i auto%ati"ally "leard in hardware when the I#R run

     (-) 0122ti"9(); // pro"e all ar%ed ti%e event  +

    9&: +he definition of e#ery /." must 'egin with the I#R() macro

    92: +he system c!ock tick must in#oke 0122ti"9() and can a!so perform other actions, if necessary

    2./ ,dle Proce""ing

    +he fo!!owing Listing 3 shows the 0122onIdle() Ica!!'ackJ function, which is in#oked repetiti#e!y fromthe Arduino loop() function whene#er there are no e#ents to process 9see ?igure 2: +his ca!!'ackfunction is !ocated in the bp!"pp fi!e in each QP sketch

    i"ting 8< Activating low-power "leep mode *or Arduino (*ile sp.%pp)

     (&) void 0122onIdle() {

     (-) O#R6*6B(); // toggle the Oer * on 8rduino on and off' ee BF& (N) O#R6*6B11();

     (L) Sifdef #8C6PBR

     (W) #AR = ($ 44 #$) < (& 44 #); // idle leep %ode' adut to your proe"t

      // never eparate the following two ae%bly intru"tion' ee BF- (>) 66a%66 66volatile66 (QeiQ QntQ 22 ); (J) 66a%66 66volatile66 (QleepQ QntQ 22 );

     (K) #AR = $; // "lear the # bit

      Sele (X) 016IF68();  Sendif  +

    &2 of /

    http://www.state-machine.com/arduinohttp://www.state-machine.com/arduino

  • 8/18/2019 An Event Driven Arduino 1.6.x

    27/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    9&: +he ca!!'ack function 0122onIdle() is ca!!ed from the Arduino !oop whene#er the e#ent %ueuesha#e no more e#ents to process 9see a!so .ection *:, in which case on!y an e1terna! interrupt canpro#ide new e#ents +he 0122onIdle() ca!!'ack is ca!!ed with interrupts di"a%led, 'ecause thedetermination of the id!e condition might change 'y any interrupt posting an e#ent

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    28/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    P4+55 i%rar7 *or Arduino™+he QP framework is dep!oyed as an Arduino !i'rary, which you import into your sketch As shown inListing *, the who!e !i'rary consists ust of three fi!es +he fo!!owing sections descri'e these fi!es

    .1 he qp_port.) Ieader =ile

    Ghen you import the !i'rary 9Arduiono /4), menu .ketch Y /mport Li'rary Y %p:, the Arduino /4) wi!! insertthe !ine ISin"lude Q3p6porthQJ into your current!y open sketch fi!e +he 3p6porth fi!e 9shown inListing &0: contains the adaptations 9port: of QP to the A" processor fo!!owed 'y the p!atform-independent code for QP +ypica!!y, you shou!d not need to edit this fi!e, e1cept perhaps when you wantto increase the ma1imum num'er of state machines you can use in your app!ications +his num'er isconfigured 'y the macro 0168M68AFIC and current!y is set to @ Eou can increase it to 65, inc!usi#e,'ut this costs additiona! memory 9"A:, so you shou!d not go too high unnecessari!y

    i"ting 1'< he >pGport.h header *ile *or the P li%rar7

    Sifndef 3p6port6hSdefine 3p6port6h

    Sin"lude 4tdinth5 // AXX.tandard e?a"t.width integerSin"lude 4avr/pg%pa"eh5 // a""eing data in the progra% %e%ory (PRBG)Sin"lude 4avr/ioh5 // #RG definitionSin"lude 4avr/interrupth5 // "li()/ei()

      // the %a"ro 06PRPFIC ele"t the pree%ptive 0 9ernel  // (default i the "ooperative QCanillaQ 9ernel)//Sdefine 06PRPFIC &  // allow uing the 0 priority "eiling %ute?//Sdefine 06OFM &

      // variou 01 obe"t i7e "onfiguration for thi portSdefine 0168M68AFIC KSdefine 016CF6#I\6#I\ &Sdefine 0160OO6AFR6#I\ &Sdefine 016PBB6#I\6#I\ &Sdefine 016PBB6AFR6#I\ &Sdefine 016FICF6AFR6#I\ -

    // the %a"ro ]PRBG] allo"ate "ont obe"t to RBSdefine 06RB PRBG

    // the %a"ro ]06RB6C8R] deignate RB obe"t^not ued in GO.8CR

    Sdefine 06RB6C8R

    // the %a"ro ]06RB6:F] read a byte fro% RBSdefine 06RB6:F(ro%6var6) pg%6read6byte6near(Z(ro%6var6))

    // 01 interrupt diable/enableSdefine 016IF6*I#8() "li()Sdefine 016IF68() ei()

    // 01 "riti"al e"tion entry/e?itSdefine 016ARIF6#F8F6F:P uintK6t

    &6 of /

    http://www.state-machine.com/arduinohttp://www.state-machine.com/arduino

  • 8/18/2019 An Event Driven Arduino 1.6.x

    29/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    Sdefine 016ARIF6FR:(tat6) do {   (tat6) = #RG;   "li(); + while ($)Sdefine 016ARIF6MIF(tat6) (#RG = (tat6))

    Sifdef 06PRPFIC  // 0 interrupt entry and e?it  Sdefine 06I#R6FR:() (06intet6)

      Sdefine 06I#R6MIF() do {   ..06intet6;   if (06intet6 == (uint6fatK6t)$) {   uint6fatK6t p = 06"hedPrio6();   if (p != (uint6fatK6t)$) {   06"hed6(p);   +   +

      + while (fale)

    Sendif // 06PRPFIC

    Sifdef 06#P: // 0# oftware tra"ing enabled,  Sdefine 0#6FI6#I\ L  Sdefine 0#6B_6PFR6#I\ L  Sdefine 0#61O6PFR6#I\ LSendif // 06#P: allow uing the 0 priority "eiling %ute?

    //TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT// *B BF AH8G 8:FHIG B FHI# I Sendif // 3p6port6h

    .& he qp_port.%pp =ile

    +he 3p6port"pp source fi!e 9shown in Listing &&: contains the Arduino-specific adaptation of QP +hisfi!e defines the Arduino loop() function, which ca!!s the QP framework to run the app!ication +hefunction 0122run() imp!ements the e#ent !oop shown in ?igure 2

    i"ting 11< he qp_port.%pp "ource *ile *or the P li%rar7

      Sin"lude Q3p6porthQ // 0P port

      //06*1I6FHI#6B*O(Q3p6portQ)

      //  e?tern QAQ void loop() {  (void)0P220122run(); //run the appli"ation' BF2 0122run() doen]t return  +

      //  Sifdef 06PRPFIC  void 06init(void) {  +  Sendif

    & of /

    http://www.state-machine.com/arduinohttp://www.state-machine.com/arduino

  • 8/18/2019 An Event Driven Arduino 1.6.x

    30/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    31/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    6 # ool" *or Arduino+he Q4PArduino /P fi!e comes with some specia! too!s, which among others a!!ow you to 'ui!d the

     Arduino proects 9sketches in the Arduino ta!k: and up!oad the code to the Arduino 'oard direct!y from the

    Q too! +his section descri'es how to use the build6avrt"l 'ui!d script as we!! as theupload6avrbat uti!ity direct!y from the Q mode!ing too!

    i"ting 1&< he tool" provided in the >pGarduinoGvarF.ip *ile

    48rduino6#9et"hboo95 . :our 8rduino #9et"hboo9 folder.tool/ . pe"ial tool for 0< ."ript/ . "ript< < .build6avrt"l @ FA "ript for building 8rduino/8CR 9et"he< < .upload6avrbat @ at"h file for uploading 8CR 9et"he

    +he Q mode!ing too! supports e1ecuting e1terna! programs direct!y from Q 'y means of the theI+oo!sJ menu and the +oo!s-too!'ar As shown in ?igure &5, the +oo!s are customi

  • 8/18/2019 An Event Driven Arduino 1.6.x

    32/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    6.1 +on*iguring he Environment Laria%le"

    +he the build6avrt"l 'ui!d script re%uires defining se#era! en#ironment #aria'!es, which you need toadust to your system through the I#anage External ool"...J dia!og 'o1

    =igure 1< he ?#anage External ool"@ dialog %ox

    +he fo!!owing +a'!e summari

  • 8/18/2019 An Event Driven Arduino 1.6.x

    33/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    B8R*6AB CD port 9needed on!y for codeup!oad and e1terna! termina!:

    ABW

    B8R*68O* aud rate of the CD Port 9neededfor code up!oad N e1terna! termina!:

    &&W-$$

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    34/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    6./ 9ploading +ode to Arduino

    +he 'atch script up!oad>a#r'at, !ocated in 48rduino6#9et"hboo95tool"ript directory uses thestandard avrdudee?e uti!ity for up!oading the code to the Arduino 'oards

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    35/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    9"ing he Preemptive : :ernel+he structure of the QPC framework for Arduino discussed in .ection &* corresponds to the simp!ecooperati#e schedu!er ca!!ed Iani!!aJ =owe#er, the QP framework can a!so e1ecute Arduino app!ications

    using the preemptive : 0ernel +he difference 'etween non-preempti#e kerne! 9!ike Iani!!aJ: andpreempti#e kerne! 9!ike Q8: is shown in ?igure &6

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    36/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

     A preempti#e kerne! can guarantee determini"tic e#ent responses posted to high-priority tasks, 'ecausethe !ower-priority tasks can 'e preempted ut this determinism comes a price of increased comp!e1ityand possi'i!ity of corrupting any shared resources among tasks A preempti#e kerne! can perform aconte1t switch at any point where interrupts are not disa'!ed 9so essentia!!y 'etween most machineinstructions: Any such conte1t switch might !ead to corruption of shared memory or other shared

    resources, and a preempti#e kerne! usua!!y pro#ides specia! mechanisms 9such as a mute1: to guaranteea mutua!!y e1c!usi#e access to any shared resources

    .1 +on*iguring the P4+55 i%rar7 to 9"e Preemptive : :ernel

    "e-configuring the QP to use the preempti#e Q8 kerne!, instead of the simp!e Iani!!aJ kerne!, is #eryeasy Eou need to define the sym'o! 06PRPFIC to the build6avrt"l 'ui!d script Additiona!!y, ifyou want to use the Q8 mute1, you need to define the sym'o! 06OFM +he fo!!owing Listing &* high!ights the changes

    =igure 1< De*ining the :GP!EE#P,LE "7m%ol in the argument" o* the  1ui&d_avr.t%& + "cript (DPP-: example)

    /2 of /

    http://www.state-machine.com/arduinohttp://www.state-machine.com/arduino

  • 8/18/2019 An Event Driven Arduino 1.6.x

    37/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    .& +hange" to the 3P *or the Preemptive : :ernel (dpp->0 Example)

    +he e1amp!e dpp.39 !ocated in the Arduino e1amp!es directory 9see Listing &: demonstrates the 4PPapp!ication descri'ed in .ection 27, running under the preempti#e Q8 kerne! +his e1amp!edemonstrates the 'sp"pp for the preempti#e Q8 kerne! +he fo!!owing Listing &* high!ights the changes

    N$E

  • 8/18/2019 An Event Driven Arduino 1.6.x

    38/39

    Copyright © Quantum Leaps, LLC A!! "ights "eser#ed

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    ; !elated Document" and !e*erence"

    Document ocation

    IPractica! BL .tatechartsin CC, .econd )ditionJVP.iCC2W, iro .amek,ewnes, 200@

     A#ai!a'!e from most on!ine 'ook retai!ers,such as Ama

  • 8/18/2019 An Event Driven Arduino 1.6.x

    39/39

    Application Note<Event-Driven Arduino™ Programming with P™

    state-machinecomarduino

    8 +ontact ,n*ormation

    uantum eap"K +

    &0* Co''!e "idge 4ri#eChape! =i!!, C 2;7&6B.A

    G)  httpwwwstate-machinecom.upportsourceforgenetproects%pcforumsforum66@;26 

    Arduino Proect

    homepage<httparduinocc

    http://www.state-machine.com/arduinohttp://www.state-machine.com/http://www.state-machine.com/http://sourceforge.net/projects/qpc/forums/forum/668726http://arduino.cc/http://www.state-machine.com/http://sourceforge.net/projects/qpc/forums/forum/668726http://arduino.cc/http://www.state-machine.com/arduino