Serial.println() and sleeping. How to completely send a message before sleeping the MCU?

Alright, so I'm doing a project that goes into a power save mode using "LowPower.h" library. But I'm having this problem that I just can't seem to get around:

My program will go into "power down" sleep mode (depending on the conditions it'll be indefinitely or 8S), but before I go to sleep I send same data out on the serial port. The problem? Unless I make it so that we go around loop() one time before we go into sleep mode the message will not send (or it will be sent incomplete). This has force me to use flags for when I need to send a message, just so I can get to the end up loo() and on the next "loop" I go into sleep mode.

Is there a way you can put data on the UART port, and wait until it is sent before moving to the next instruction?

This will cause the program to wait till all bytes have been transmitted.

2 Likes

Yes and no. Serial.flush() outputs everything in its queue, but if the queue is empty the last character is just being transmitted. So calculate the time for transmission of a character, depending on the actual baudrate, and leave at least as much time before going asleep.

Or find a flag in your controller that tells that the UART is really idle. Better twice that time, if the UART output is double buffered.

EDIT: fixed in the meantime, see following post :slight_smile:

on AVR, it seems it does the right thing and waits for the last bit to be out.

This is the comment at the end of the flush() function

on ESP32 I think it does check both that the FIFO is empty and there is nothing left in transmission

1 Like

Thanks for the update. The AVR code it looks different from my first review a few years ago.

got it - yes they changed a few things over the year

That did the trick. Thank!!

I tried Serial.flash() and added a delay(10) to make sure the last character is transmitted. And it seems to be working fine. I managed to get rid of all the flags I had to circle around loop() and it made debugging so much easier.

I'm using a homebrew board with the 328p but I'm using the Arduino IDE to code.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.