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);
}
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.

  • 2
    And from this answer (assuming more than 1000 bytes of RAM) the UART's buffer will be 64 bytes, which is just enough to hold the remaining 15 numbers (two bytes + CR + LF each) with four bytes left over. – TripeHound Apr 19 '18 at 18:53
  • I wouldn't say that one shouldn't call exit() on a microcontroller. Rather, one shouldn't call a simple infinite loop exit(), suggesting it's a proper POSIX function. – Dmitry Grigoryev Apr 20 '18 at 12:25

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.