【问题标题】:Stop timer set new value and start again AVR (Interrupt)停止定时器设置新值并重新启动 AVR(中断)
【发布时间】:2015-04-14 20:49:10
【问题描述】:

我有 AVR MCU。
我现在正在玩计时器。
我需要的 ?我有计时器以某种频率计数。在每个中断中,我都在递增变量,在某个地方我需要检查这个变量的值,如果等于 100,我需要停止计时器计数,为频率设置新值并继续倒计时。
我无法了解如何停止计时器并设置新值进行比较。
我尝试使用多路复用器选择器寄存器不选择时钟源,但它继续计数。
这样做的正确方法是什么。 这是我的代码

// Arduino timer CTC interrupt example
// www.engblaze.com

// avr-libc library includes
#include <avr/io.h>
#include <avr/interrupt.h>

#define LEDPIN_UP 9
#define LEDPIN_DOWN 8
int current_value = 0;
void setup()
{
   Serial.begin(9600);  
   // pinMode(LEDPIN_UP, OUTPUT);

    // initialize Timer1
    cli();          // disable global interrupts
    TCCR1A = 0;     // set entire TCCR1A register to 0
    TCCR1B = 0;     // same for TCCR1B

    // set compare match register to desired timer count:
   // OCR1A = 3123;
    OCR1A = 1562;
    // turn on CTC mode:
    TCCR1B |= (1 << WGM12);
    // Set CS10 and CS12 bits for 1024 prescaler:
    TCCR1B |= (1 << CS10);
    TCCR1B |= (1 << CS12);
    // enable timer compare interrupt:
    TIMSK1 |= (1 << OCIE1A);
    // enable global interrupts:
    sei();
}

void loop()
{
    //digitalWrite(LEDPIN_UP, current_value);
  Serial.println(current_value);
       if(current_value==255) {
      TCCR1B |= (0 << CS10);
      TCCR1B |= (0 << CS12);
      Serial.println("Reseting timer");
    }
}

ISR(TIMER1_COMPA_vect)
{
    current_value++;

}

【问题讨论】:

    标签: timer arduino microcontroller interrupt avr


    【解决方案1】:
      TCCR1B |= (0 << CS10);
      TCCR1B |= (0 << CS12);
    

    不符合您的预期。由于您使用的是“或”|,因此放回的值是 0|1,即 1,而不是您想要的 0。

    清除位的常用方法是

      TCCR1B &= ~(1 << CS10);
    

    要一次清除两个位,请使用

      TCCR1B &= ~(1 << CS10 | 1 << CS12);
    

    至于倒计时,您将需要使用一个变量来指示您当前前进的方向,然后在 ISR 中使用该变量。也许,

    int dir = 1;
    
    ISR(TIMER1_COMPA_vect)
    {
        current_value += dir;
    }
    

    当您希望它倒计时时,将 dir 更改为 -1。

    【讨论】:

      猜你喜欢
      • 2013-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-19
      相关资源
      最近更新 更多