loop termination prematurely?

Hello,

i am executing this code on arduino uno:

#include <avr/interrupt.h>
#include <avr/sleep.h>
int count=1;

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);

}

void loop() {
// put your main code here, to run repeatedly:
Serial.print(“hihi”);
Serial.println(count);
count=count+1;
if (count==200){
Serial.println("*");
Serial.println(count);
stop();
}

}

void stop(){
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
cli(); //Disable interrupts
sleep_mode();
}

the com3 output in the end is this:


hihi189
hihi190
hihi191
hihi192
hihi1

it should stop at 200 but it stops prematurely. Even the lines

Serial.println("*");
Serial.println(count);

are not executed.
Am I missing something here?

Speed up you baud rate.

https://www.arduino.cc/en/Serial/Flush

You're missing the fact that serial output is buffered.

It looks like you are pitting the Uno to sleep before it has printed all of the output.

Insert a Serial.flush() before calling stop()

Speeding up baud rate won't make much of a difference, if any - that code is easily filling the buffer (so the later calls to Serial.print() are blocking waiting for room in the buffer), so stop() gets called with a full buffer, and you lose about 1 buffer-worth of messages. ~64 bytes are lost, which is exactly what you'd expect.

a Serial.flush(); at the start of stop function does the trick, without changing the baud rate! Thank you guys for your time on this!