I have an ATmega1284p and I need to have the TXD0 (i.e. pin 9) set to LOW, before going to sleep. After waking up, I want to restore UART0 communication to work as expected. Here is my code:
Serial.begin(38400,SERIAL_8N1);
*do Stuff*
Serial.end();
//pinMode(9,OUTPUT);
//digitalWrite(9,LOW);
//UCSR0B &= ~bit (RXEN0); // disable receiver
//UCSR0B &= ~bit (TXEN0); // disable transmitter
cli();
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
sleep_enable();
// turn off brown-out enable in software
//MCUCR = bit (BODS) | bit (BODSE); // turn on brown-out enable select
//MCUCR = bit (BODS); // this must be done within 4 clock cycles of above
sleep_bod_disable(); //disable brown-out detection
sei(); // guarantees next instruction executed
sleep_cpu (); // sleep within 3 clock cycles of above
sleep_disable();
// UCSR0B |= bit (RXEN0); // enable receiver
// UCSR0B |= bit (TXEN0); // enable transmitter
//pinMode(9,OUTPUT);
//digitalWrite(9,HIGH);
//delay(100);
//pinMode(9,INPUT_PULLUP);
Serial.begin(38400,SERIAL_8N1);
delay(1000);
Serial.println("- Good Morning");
*do Stuff*
You can see in comments all the different things I tried:
- Using
Serial.end()
and then, after waking up,Serial.begin()
- Using the
UCSR0B
register - Using
digitalWrite
to set the pin toLOW
and then, after waking up, either setting it tohigh
, or setting it asinput
All of the above combinations have the common problem that the cpu hangs after waking up, and the Serial is never restarted to print good morning
message, neither does the program continue to execute further down.
Serial.println
might block then and that would be the reason your program won't be executed any further. Again; these are just guesses, but worth a try. ;-) Did the sleep mode work without the Serial shutdown? Can you try "the further processing" with out anyprintln
to see if the prints block or not? Can you recognize "further processing" without print statements?#if 0 // try 1
...#elif 1 // try 2
...#endif
.delay(1000);
after* do Stuff*
. My guess is that there is still data being send over the serial connection when the MCU is put to sleep; leading to weird issues.Serial.flush()
. Of course, both would work fine