2016-04-24 897 views
1

我嘗試停下來,重新恢復我的Arduino的中斷定時器他算什麼後500 所以,中斷定時器計數到500,然後拖延幾秒鐘,然後再恢復中斷定時器問:如何啓動和停止Arduino上的中斷定時器?

這是我的代碼,我可以停止中斷,但不知道如何延緩和恢復定時器再次

#define ledPin 13 
int count=0; 
void setup() 
{ 
pinMode(ledPin, OUTPUT); 
Serial.begin(9600); 
cli();//stop interrupts 
//set timer0 interrupt at 2kHz 
    TCCR1A = 0;// set entire TCCR0A register to 0 
    TCCR1B = 0;// same for TCCR0B 
    TCNT1 = 0;//initialize counter value to 0 
    // set compare match register for 2khz increments 
    OCR1A = 124;// = (16*10^6)/(2000*64) - 1 (must be <256) 
    // turn on CTC mode 
    TCCR1A |= (1 << WGM01); 
    // Set CS01 and CS00 bits for 64 prescaler 
    TCCR1B |= (1 << CS01) | (1 << CS00); 
    // enable timer compare interrupt 
    TIMSK1 |= (1 << OCIE1A); 
sei(); 
} 

ISR(TIMER1_COMPA_vect) // timer compare interrupt service routine 
{ 
count++; 
if(count%2==0)digitalWrite(ledPin,HIGH); 
if(count%2==1)digitalWrite(ledPin,LOW); 
if(count>=500) 
{ 
    count=0; 
    TCCR1B=0; 
    digitalWrite(ledPin,LOW); 
    //TCCR1B |= (1 << CS01) | (1 << CS00); 
} 

} 

void loop() 
{ 
// your program here... 

Serial.println(count); 
delay(1000); 

} 

void berhenti() 
{ 
cli();//stop interrupts 
digitalWrite(ledPin,LOW); 
count=0; 
delay(3000); 
sei(); 
} 
+0

名爲「berhenti()」的例程的目的是什麼?你有沒有把這個例程叫做? – mhopeng

回答

0

可以使用millis()函數來計算你所需要的時間。

#define ledPin 13 
int count=0; 

// A boolean to know if the timer is stopped or not. 
// You can use the TIMSK1 bit, but I prefer a seperate variable. 
boolean timerStopped = false; 

// Time when the timer stopped. 
long timerStoppedTime = 0; 

// Your delay in milliseconds. 
// You can use a macro here as well. 
long timerStoppedDelay = 1000; 

// I'll explain this variable in the answer. 
boolean takeTimeTimerStopped = true; 

void setup() 
{ 
    // I haven't change this function. 
} 

ISR(TIMER1_COMPA_vect) // timer compare interrupt service routine 
{ 
    count++; 
    if(count%2==0)digitalWrite(ledPin,HIGH); 
    if(count%2==1)digitalWrite(ledPin,LOW); 
    if(count>=500) 
    { 
     count=0; 
     TCCR1B=0; 
     digitalWrite(ledPin,LOW); 
     TIMSK1 |= (0 << OCIE1A); // deactivate timer's interrupt. 
     timerStopped = true; 
    } 

} 

void loop() 
{ 
    // your program here... 

    Serial.println(count); 
    delay(1000); 

    if(timerStopped) 
    { 
     if(takeTimeTimerStopped) 
     { 
      timerStoppedTime = millis(); 
      takeTimeTimerStopped = false; 
     } 
     if((millis() - timerStoppedTime) >= timerStoppedDelay) 
     { 
      TIMSK1 |= (1 << OCIE1A); // reactivate the timer. 
      timerStopped = false; 
      takeTimeTimerStopped = true; 
     } 
    } 

} 

您需要takeTimeTimerStopped布爾在每次進入if(timerStopped)語句時不會改變timerStoppedTime。 避免這種醜惡東西的合理方法是在ISR中花時間。 但millis()它自身使用定時器0中斷計數,在http://www.arduino.cc/en/Reference/AttachInterrupt

說明。此外,在您的loop函數每次調用dealy()將進一步拖延重新激活您的計時器的時間不應該被稱爲ISR內。你也需要考慮這一點。