Vous êtes sur la page 1sur 1

201764 ArduinoTimerInterrupts

GiftVoucher SpecialOffers Bookmark Contact Sitemap

Home LogIn Account Compare Basket Checkout


AllourpricesincludeVAT
wedon'taddVATatthecheckout

Home>ArduinoTimerInterrupts PoundSterling

ArduinoTimerInterrupts

ArduinoTimerInterrupts
Whenyouwantthingstohappenataregulartimeinterval,itcanbeeasytogoforthedelay()function.
Butthisjustpausestheprogramforaspecifictimeperiodwhichiswastefulespeciallyifyouneedtodo
otherprocessinginthemeantime.

Thisiswheretimersandinterruptscomeintoplay.

TheArduinoUNOhasthreetimers

Timer0An8bittimerusedbyArduinofunctionsdelay(),millis()andmicros().
Timer1A16bittimerusedbytheServo()library
Timer2An8bittimerusedbytheTone()library

TheMegaboardshaveTimers3,4,5whichmaybeusedinstead

Intheexamplethatfollows,weshalluseTimer1forourinterrupt.Obviously,ifyouareusingtheServo
Librarytherewillbeaconflict,soyoushouldchooseanothertimer.

Hereisthebasicsofaninterruptdrivenprogram.ItisthebasicLEDflashprogram,butnowinsteadof
usingdelaysitusesaninterrupteveryhalfsecondtoturntheLEDonandthenoff,thusmakingtheLED
flashoncepersecond.

/*
ExampleTimer1Interrupt
FlashLEDeverysecond
*/

#defineledPin13
inttimer1_counter
voidsetup()
{
pinMode(ledPin,OUTPUT)

//initializetimer1
noInterrupts()//disableallinterrupts
TCCR1A=0
TCCR1B=0

//Settimer1_countertothecorrectvalueforourinterruptinterval
//timer1_counter=64911//preloadtimer6553616MHz/256/100Hz
//timer1_counter=64286//preloadtimer6553616MHz/256/50Hz
timer1_counter=34286//preloadtimer6553616MHz/256/2Hz

TCNT1=timer1_counter//preloadtimer
TCCR1B|=(1<<CS12)//256prescaler
TIMSK1|=(1<<TOIE1)//enabletimeroverflowinterrupt
interrupts()//enableallinterrupts
}

ISR(TIMER1_OVF_vect)//interruptserviceroutine
{
TCNT1=timer1_counter//preloadtimer
digitalWrite(ledPin,digitalRead(ledPin)^1)
}

voidloop()
{
//yourprogramhere...
}

http://www.hobbytronics.co.uk/arduinotimerinterrupts 1/1

Vous aimerez peut-être aussi