设置一个标志并不在我的定时器中断工作(而中断工作)

问题描述 投票:0回答:1

我以前写我在ICCAVR代码和我有没有问题,但由于某种原因,我应该迁移到AtmelStudio。在下面的代码,LED灯闪烁的中断,但是当我只在中断设置标志,并希望在闪烁轮询LED(使用标志)它不会工作:

#include<avr/io.h>
#include<avr/interrupt.h>

#define LED PA1


ISR (TIMER1_OVF_vect)    // Timer1 ISR
{
    //PORTA ^= (1 << LED);
    TCNT1 = 63974;   // for 1 sec at 16 MHz
    PORTA ^= (1 << LED);
}

int main()
{
    DDRA = (0x01 << LED);     //Configure the PORTD4 as output

    TCNT1 = 63974;   // for 1 sec at 16 MHz

    TCCR1A = 0x00;
    TCCR1B = (1<<CS10) | (1<<CS12);;  // Timer mode with 1024 prescler
    TIMSK = (1 << TOIE1) ;   // Enable timer1 overflow interrupt(TOIE1)
    sei();        // Enable global interrupts by setting global interrupt enable bit in SREG

    while(1)
    {

    }
}

而这种变化将使其不闪烁:

#include<avr/io.h>
#include<avr/interrupt.h>

#define LED PA1

unsigned int counter=0;
unsigned char flag=0;

ISR (TIMER1_OVF_vect)    // Timer1 ISR
{
    //PORTA ^= (1 << LED);
    TCNT1 = 63974;   // for 1 sec at 16 MHz
    counter++;
    if(counter>=10)
    {
        flag=1;
        counter=0;
    }
}

int main()
{
    DDRA = (0x01 << LED);     //Configure the PORTD4 as output

    TCNT1 = 63974;   // for 1 sec at 16 MHz

    TCCR1A = 0x00;
    TCCR1B = (1<<CS10) | (1<<CS12);;  // Timer mode with 1024 prescler
    TIMSK = (1 << TOIE1) ;   // Enable timer1 overflow interrupt(TOIE1)
    sei();        // Enable global interrupts by setting global interrupt enable bit in SREG

    while(1)
    {
        if(flag)
        {
            flag=0;
            PORTA ^= (1 << LED);
        }
    }
}

任何人都可以帮我吗?

timer interrupt avr avr-gcc atmelstudio
1个回答
1
投票

编译器看到flag在程序开始时设置为0,也无法知道该变量可以通过中断处理程序(从不直接调用的程序代码)来改变。因此,优化出flag循环while检查。

使用volatile预选赛,从不同的码流访问的变量(主代码和中断处理程序,在多线程环境中不同的线程)。

volatile unsigned char flag = 0;
© www.soinside.com 2019 - 2024. All rights reserved.