It looks that there is some problem - maybe softwareserial library does not stop properly?
Case (Arduino Mega):
Start SoftwareSerial on pins 22+A9 and detect sensor. If response from sensor is received, use that sensor.
If not, end SoftwareSerial, then start I2C on pins 22+23 and detect sensor.
OP want to makes a device that can plug / unplug two types of sensors (one that uses UART and one that uses I2C) into one external connector port?
So he came up with wanted to use a UART with exactly the same pins of I2C?
Well, even if this imagine is correct...
I think that it is possible to bundle multiple pins by correctly controlling the initialization of the pins and setting the unused interface side to Hi-Z.
Although there are still have output confliction risks with coding misses.
I didn't wanted to mention it here...I have a PCB to which Arduino is connected. There are external ports for many sensors, some serial, some I2c, some OneWire. Customer has a choice which sensors connect to what port, so it has to be universal - Arduino must detect a sensor and then use it.
@srnet 3 is not enough and it can not be used as we need it. @chrisknightley It's not both the same pin, see first post. Only one of them is the same, because of PCB under Arduino, see answer in this post. "bundle multiple pins by correctly controlling the initialization of the pins and setting the unused interface side to Hi-Z" - i will discuss this with developer, thanks.
At least tell us which pin is what.
The Arduino Mega 2560 has no I2C bus at pin 22 + 23. Do you want to use a software I2C bus ?
When the SDA is kept high, the SCL pin may be used for other things.
However, if SDA is involved in any way and then you change from Serial to I2C, then the I2C bus might get stuck. That can be unstuck, but might not always work 100%.
Suppose the customer changes a module while the Arduino is running, then there is probably no way to make that 100% reliable.
The RS-485 (a version of Serial communication) is hot swappable.
I'm not sure, but perhaps the SBus (a version of I2C communication) migh be hot swappable.
Combining those with the same wires is not possible.
As you can see, there are many possibilities, but also many things that can go wrong.
Sounds like a bad idea to do it this way. Better decide on a universal interface between the Arduino and all possible sensors and a translator/bridge between that universal interface and the various sensor interfaces. The universal interface would have to be both a hardware component and a software component. You basically have that challenge now already, but apparently you're solving the latter in the Arduino in an unspecified way.
How about using a six pin connector, with 2 pins for 5V and GND, 2 pins for UART transmit and receive, and 2 pins for I2C clock and data.
Then when you wire up the sensor you just connect to the appropriate 4 pins.