Using a transistor for interfacing different voltages
Normally, you connect the grounds of your MCU power supply (3.3 &amp; 5V) and your solenoid power supply (12V), in a circuit like this:







simulate this circuit &ndash; Schematic created using CircuitLab

If this is undesired for some reason, then you'll have to employ some device to galvanically separate the MCU from the solenoid, eg an opto-coupler:







simulate this circuit



The resistor values should be calculated based on the desired current through the transistor / LED and the known voltages (forwarding voltage of the base-emitter diode / LED, GPIO high-level output). For both the transistor stage &amp; the LED in the opto-coupler, a margin of 1:5..1:20 is desireable to keep the output saturated. So you calculate the output current needed, divide it by the data sheet typical hFE / CTR figures and multiply it by 5..20. The "pull-down" resistor should be sized to take a smaller fraction (~5-15%) of the calculated base current.