Condition after interrupt only meet, if previously printed

Hello Guys,

I made a mistake I can’t understand. It’s a bit like quantum physics. If you watch, it is were you think it is. If not, it’s everywhere.

I’m counting up a int „i_timer“ every time a timer interrupt is triggered. My main program is waiting in a while till i_timer is bigger then 0.

The problem:
The “if” condition inside the while only is meet if i_timer is printed in every circle of the while.
When i_timer is not printed, the condition is never meet.
I tried different delays instead of the print, to make sure is not related to the time spent printing.
The serial.print Funktion somehow must erases some mistake I made. Maybe someone knows what it could be, so I can find my mistake.

Here you can see the vital Funktion for the Problem.


void Output_End()
{
  Next_OCR=30000;
  i_timer=0;
  while(1)
  {
    //Serial.println(i_timer); //why
    //delay(0.1);

    if(i_timer>0)
    {
      noInterrupts();
      TIMSK1 |= (1 << OCIE1A);
      toggle = false; 
      digitalWrite(OUTPUT_PIN, toggle); 
      return; 
    }
    else
    {
      delay(0.1);
    }

  }
}

ISR(TIMER1_COMPA_vect)          // timer compare interrupt service routine
{
  noInterrupts();
  OCR1A=Next_OCR;
  i_timer++; 
  toggle = !toggle; 
  digitalWrite(OUTPUT_PIN, toggle);
  TCNT1  = 0;
  interrupts(); 
 
}

void Output_Begin()
{
  i_timer=0;
  toggle=false;
  digitalWrite(OUTPUT_PIN, toggle);
  Next_OCR=BEGIN_LEVEL_DURATION;
  // initialize timer1 
    noInterrupts();           // disable all interrupts
  
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1  = 0;
    
    OCR1A = BEGIN_LEVEL_DURATION;            // compare match register 16MHz/8/2Hz
    TCCR1B |= (1 << WGM12);   // CTC mode
    TCCR1B |= (1 << CS11);    // 8 prescaler
    TIMSK1 |= (1 << OCIE1A);  // enable timer compare interrupt
    TCNT1  = 0;
  
    interrupts();             // enable all interrupts

    
  while(1)
  {   
    if(i_timer==1)
    {
      //Next_OCR=begin_array[0];
      //Serial.println(i_timer);
      Next_OCR=BEGIN_BREAK;
      delay(.1);
    }
    else if(i_timer==2)
    {
      //Serial.println(i_timer);
      //Next_OCR=begin_array[1];
      Next_OCR=LEVEL_DURATION;
      delay(.1);
    }
    else if(i_timer>2)
    {
      return;
    }
    
  }
  return;
}


Im guessing English isn’t your first language…

You may have more luck if you pose your question in the language specific section of the forum.

This kind of problem with interrupts often means that you forgot to declare a variable 'volatile'. You didn;t show your declarations so it's hard to tell which one.

1 Like

Interrupts are automatically disabled inside an ISR and are automatically enabled when the ISR returns DO NOT disable and enable interrupts in an ISR.

1 Like

Thank you very much. That was the solution for my problem. You can’t imagine how much that helped me.