I have arduino Leonardo with I2C LCD, the whole setup is powered via external power supply going to VIN pin on the Leonardo. Sometimes I need to connect/dosconnect USB as iam using computer for some MIDI communication, when I connect the USB
to the Leonardo it usually messes up the I2C comms, not every time but very often. Is there any way to prevent this?
Suppose you have a cheap power supply and its 0V differs too much from the USB GND from the computer. When you connect those, then there might be a large noise peak going through everything in your circuit.
The I2C bus is a weak bus. You can make it less weak by adding pullup resistors for SDA and SCL.
Suppose that you have a cable or flat ribbon cable and SDA is next to SCL. Then your I2C bus is barely working and everything will disturb the I2C communication.
Your I2C wires could be too long.
Perhaps the GND of the I2C bus is also used for something else, then you create a noisy I2C bus.
I can go on and on, but perhaps it is easier if you show a photo with the wiring.
I am using MEAN WELL 5V 1A switching power supply, I also have 10k pull-ups on both SDA and SCL, the lines indeed goes next to each other but it is just few cms long, just from the arduino board to the LCD, both are in a small plastic box.
If you use a flat ribbon cable, please split the wires of that cable.
Sometimes a project can be made to work with a larger capacitor to 5V and GND (100µF to 1000µF).
Grounding is a craftsmanship on its own. You could have a Arduino clone that barely works.
Does your Mean Well power adapter have a earth ground in the plug ? And is that connected to the earth ground of your mains ?
Do you have a USB charger of 5V ? Try that, or a power bank, or a laptop or a desktop computer. Perhaps that makes a difference.
It looks like something that I had in the past. I had the same problem with a Arduino Mega 2560 board, and I never solved it. The board was a finicky clone board.
These things can be very hard to solve. I can think of more things, but me trying to mention every possible problem with so little information seems a waste of my time.