I realized that a part of my circuit that is supposed to be turned off is drawing parasitic power from TX2 (pin 16) on my Arduino MEGA2560 board. I tried to digitalWrite(16,LOW); to turn it off but it won't turn off. Only Serial2.end() actually turns it to LOW. I was wondering why. My guess is the UART hardware is driving this pin so the usually digitalWrite is no longer affecting it. Can someone explain this? Thanks.
At any point does your sketch call Serial2.begin? If the answer is yes then, yes, the UART hardware is driving the pin until your sketch calls Serial2.end.
The idle state of a UART is logic high. While the serial port is enabled, it holds TX high (except when it's transmitting data, ofc). You can call Serial2.end(), or manually unset the TXEN bit of the UCSR2B to disable transmit (and set it back to reenable it).
Yes, my sketch calls begin in setup. If it doesn't call begin then I can change the state of the pin using digitalWrite. So my solution is to call end in a power_off function so the UART hardware will stop pulling the TX2 pin HIGH. Then in a power_on function, I call begin again. The code ran fine for an hour or so. More tests are needed to see if repeated calls to begin and end may expose some problems.
DrAzzy:
The idle state of a UART is logic high. While the serial port is enabled, it holds TX high (except when it's transmitting data, ofc). You can call Serial2.end(), or manually unset the TXEN bit of the UCSR2B to disable transmit (and set it back to reenable it).
Thanks. I'll try this one. It sounds easier than repeatedly calling begin and then end. I really don't need to do anything more than turning off the idle HIGH state, as you said.