I'm seeing some odd behavior regarding the Serial output when waking the Arduino from sleep mode.
#include <avr/sleep.h>
#include <avr/power.h>
void setup()
{
Serial.begin(9600);
Serial.println("leaving setup");
}
void loop()
{
Serial.println("sleeping...");
Serial.flush();
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
attachInterrupt(0, pin2Interrupt, LOW);
sleep_mode();
// sleeping
sleep_disable();
delay(1000);
Serial.println("awake");
}
void pin2Interrupt()
{
detachInterrupt(0);
}
I see the following output:
leaving setup
sleeping... Cáawake
sleeping... Cáawake
sleeping... Cáawake
I'm not sure why the "Cá" is printed. Also the line break is missing. I have pin2 attached to a 555 timer circuit to wake the Arduino every eight seconds via interrupt.
Any ideas as to what is causing this?
First thing I would do is add a delay between printing and sleeping. If the line terminator works it probably means the sleep process is shutting down the serial hardware before it finishes sending.
EDIT: I just checked the core sources and 'flush()' just waits until the software buffer is empty. It does not waiting for the last byte to clear the hardware buffer.
I'm not sure if the TX pin idles HIGH or LOW. If it's HIGH you may need a pull-up resistor to keep the line HIGH while the processor is sleeping.
The flush doesn't wait for that last byte to be transmitted, so you are sleeping too soon. A delay before the sleep would help, but to be precise, add these lines after the flush. That waits until the transmit buffer is empty:
void loop()
{
Serial.println("sleeping...");
Serial.flush();
while (!(UCSR0A & (1 << UDRE0))) // Wait for empty transmit buffer
UCSR0A |= 1 << TXC0; // mark transmission not complete
while (!(UCSR0A & (1 << TXC0))); // Wait for the transmission to complete
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
attachInterrupt(0, pin2Interrupt, LOW);
sleep_mode();
// sleeping
sleep_disable();
delay(1000);
Serial.println("awake");
}
Plus what johnwasser said while I was typing. The resistor may help, although in my test it was OK without it.
I tried delay(10) and the registers in separate tests and both worked. I didn't try the resistor. Thank you both for your help.