7
int a[100],i;
void setup() {
  Serial.begin(9600);
}

void loop() {
  for(i=0; i<100; i++) {
    a[i] = i;
    Serial.println(a[i]);
  }
  exit(0);
}
dda
  • 1,595
  • 1
  • 12
  • 17
Anurag
  • 71
  • 2

1 Answers1

27

It's because you're using exit(0). That turns off interrupts and goes into an infinite loop. However, serial printing is first placed into a buffer, and each character is then removed from that buffer in turn and sent out through the serial port.

That's all fine, up until the end when you use exit(0);, and what is left in the serial buffer to send never gets sent because interrupts are disabled.

There is never really any cause to use exit() on a microcontroller - after all, where can it "exit" to? There's no OS to exit to. So it does the next best thing which is as close to doing nothing as reasonably possible.

Instead, if you want to "stop" your program you should use a simple while(1); which will allow interrupts to still trigger.

Alternatively, if you really want to use exit(), you should flush the serial first:

Serial.flush();

That function will block until the transmit buffer has been fully emptied by the interrupt and the last byte has left the UART's TX shift register.

Majenko
  • 105,851
  • 5
  • 82
  • 139