-1

to describe my problem, i share a short code with arduino here:

int index=0;

void setup()
{
  Serial.begin(9600);
  noInterrupts();
  TCCR1A=0; // RESET
  TCCR1B=0; //RESET
  TCNT1=0;

  TCCR1B |= (1<<CS12);  // clk/256 prescaling
  TCCR1B |=(1<<WGM12);  // ctc mode
  OCR1A= 6250;          // 10 Hz
  TIMSK1 |=(1<<OCIE1A);
  interrupts();
}

ISR(TIMER1_COMPA_vect)
{
  index++;
  Serial.println(index);
}

void loop()
{
  if (index == 100)
  {
    Serial.println("code's here");
    noInterrupts();

  }
}

output i expect:

1
2
3
...
...
100
code's here

output i get:

1
2
3
...
...
98
99
10

So my Serial.println("code's here") is not working. i dont understand why. in fact nothing in my void loop works, while I code like this. what does this noInterrupts do actually?

please give me an explanation. any help is appreciated.

srquinn
  • 10,134
  • 2
  • 48
  • 54
morshed005
  • 1
  • 1
  • 1
  • Then post your answer? Why would you say you just figured it out without giving the solution? What if someone else comes along with this same exact problem? – DotNetRussell Dec 19 '13 at 04:30
  • alryt i just got a way to sort out this i had to include "TIMSK1 &= ~(1 << OCIE1A)" in place of "noInterrupts()" but still i dont understand what noInterrupts() do. i hope anubody can put some light on that. – morshed005 Dec 19 '13 at 04:37
  • "#define noInterrupts() cli()" as found in \hardware\arduino\cores\arduino\Arduino.h. So it is nothing special. Just disables all interrupts. Likewise "#define interrupts() sei()" turns them back on. – mpflaga Dec 19 '13 at 15:11

1 Answers1

0

You are using the Hardware Serial, which in turn uses interrupts for transmitting. The Serial.print fills a buffer and then enables the transmitter empty interrupt, so that it will send each char in the background, per interrupt as your code moves on. Hence noInterrupts() just after a Serial.print immediately stops all interrupts leaving it no time to begin the transmitter interrupts. Hence you get nothing.

Note that the "10" you initially got at the end is first two digits of the 100. Speed the baud rate up to 115200 and you get the whole 100. In that the Serial ISR occurs faster.

Where as you mentioned changing the above code to the following fixes the issue. In that only the Timer Interrupt is stopped, allowing the Serial Interrupt and others to continue on.

void loop()
{
  if (index == 100)
  {
    Serial.println("code's here");
    //noInterrupts();
    TIMSK1 &= ~(1 << OCIE1A);
    while(1);
  }
}

The moral of the story is stop and start things specifically. As you may not know exactly what else is going on in the background.

mpflaga
  • 2,807
  • 2
  • 15
  • 19