Determine serial pins from serial being used.


Bit of a strange question.

Suppose you have a sketch which you do a Serial1.begin(9600); in the setup().
Is there a way, to determine from this, what pin on the particular Arduino hardware you are using, this is, so it can be used to dictate something else?

Basically what I am trying to do involves the ability to recover from a failure of a connected device on serial. I have code which can recover, if it knows something has gone wrong, but at the moment when the power is pulled from the remote device, Serial1 RX pin is floating, its not pulled high or low.
Short of adding to the hardware, I thought we could take advantage of the internal pullup.

So, if there was a way to determine the pin from the UART that we are using Serial1, then add a line to enable that UART's RX pin, to be Internal Pullup. pinmode(Serial1_RX, INPUT_PULLUP);
for example.

Works find manually defining, it, pinmode(19, INTERNAL_PULLUP) after doing the Serial1.begin(9600); statement.

Serial1 on one Arduino, is likely a different pin to another Arduino.

Just curious if there might be any way to determine this from the sketch. Just trying to make this a little more universal.


You can't. You however can basically use an approach as is used in the libraries with #defines. Have a look how it's done in e.g. Arduino.h (see below)

#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644__) || defined(__AVR_ATmega644A__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644PA__)

Adjust to your needs and replace the dots by something useful.

If you search for __AVR, you will find more definitions (e.g. AVR_ATmega328P (e.g. in pin_defs.h)
The code in the sketch could look like

#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
#define RXPIN 0
#if defined(__AVR_ATmega1280__)
#define RXPIN 999

Can't test and play at this moment to help further. If you use RXPIN somewhere in your code and it's not defined for a certain processor, your code will not compile.