I've got an idea for a project but there's a detail I need a little help with.
I will have two Arduinos that will communicate via serial. The Arduinos won't always be connected so I need to detect when they are connected and should be communicating.
I am trying to think of a wiring/pin configuration that will allow both Arduinos to sense when they are connected to each other. This is simple with two sense wires, but ideally, I would like to do it with one. wire.
if the arduinos are connected via serial they could regularly poll each other to see if the other is awake, e.g. transmitting an ESC character. On recipt of an ESC the other will respond, e.g. with ACK. If ACK is not received within a specified time it an be assumed the other machine is not available.
I thought of something similar to this but was worried that the serial buffers could get into a strange state since the Arduinos can be disconnected from each other at any time.
Feels like I would need to flush the serial when they disconnect?
No, if they are not connected or if they are connected and sending nothing the results will be the same. I can't see what difference would be and why you would need to know.
For a Uno you need to wire the TX of one to the RX of the other, using pins 0 and 1.
Say one Arduino is sending a byte but they are disconnected halfway through. Doesn't the RX buffer on the destination had four bits in its shift register that need clearning?
you need to work out a protocol indicating start of message - data - end of message
possibly with a CRC for error checking
does the receiver need to acknowledge recipt?
what type of data are you transmiitting? ASCII text, binary, ??
The receiving Arduino will take whatever level is on the Rx line and use it as the final few bits to complete the character - serial is an asynchronous protocol, so the receiver generates the timing based on the start bit, regardless of whether the sender is actually sending all the bits or not. As to what the receiving Arduino does with that final character depends on your code, it would probably be a good idea to implement a checksum or crc code with each message to assure that it is valid, and discard invalid messages.
for reliable serial communications I use a protocol where a frame is encoded so (with DLEs being byte stuffed)
SYN DLE STX byte stuffed data CRC DLE ETX
can check for corrupt frames, lost bytes, etc and in case of problems request retransmission
the data can be text or binary (integers, floats, structures, etc)