Is there a way to have a sensor be hot swappable, as in it can be disconnected and reconnected without locking up the Arduino? I have an I2C sensor that I want to be able to disconnect and reconnect without having to restart the board.
The I2C bus is not blocking the operation, if the sensor isn't there. Also the
Wire library will not block in this case. It will just return an error code, which you should handle in your code.
But this doesn't mean, that every library, which wraps the I2C workload for a specific sensor, is doing the same. Depending on the sensor and the used library you will have to check yourself, if it is blocking in any way. (This part is not better answerable without information on what sensor and what library will be used)
So: Yes, this is totally possible, but you will have to deal with the errors from disconnecting the sensor and handle them in your code. By polling the sensor in a regular fashion (like Jot mentioned in the comments) will give you the information, if there is a sensor with this address on the bus. The
Wire.endTransmission() method will return
2 (received NACK on transmit of address), if no device with the specified address is reachable on the bus.
Depending on the used sensor, you might have to initialize the sensor correctly after every reconnect. Especially, if the disconnect happend during a transmission. Refer to the datasheet of the sensor to find out, what happens in this case with the sensor.
If you plan to use different sensors, you have to check for their specific addresses (since different types of sensor often have different hardwired addresses/address spans) and - if the sensors are controlled differently - determine, what sensor is actually connected. The least may be possible by reading their status registers, which can work for many sensor types.