Hoping someone might be able to help me. I am looking to connect an RPI to a car and use the ignition voltage to signal to the RPI to shutdown. I have the constant voltage part sorted but I just need guidance with the GPIO configuration and sensing the drop in voltage from the car. Basically I have purchased optocouplers (PC817X2NSZ0F) and have a selection of resistors. I understand the voltage is going to be somewhere around 7 - 18 volts so I was going to use a high enough resistor to adjust for this over the diode. Do you think this should work?
I suspect your range of 7--18V is too broad, but taking it on trust for the moment:
At 18V you'd need (approximately) a 330Ω resistor for the rated 50mA of current. You'd dissipate over 800mW of heat in the resistor, so you'd be looking for a fairly large resistor (rated 1W). Alternatively 3 resistors in parallel, each 1/2W 1KΩ would do the trick. At 7V this resistor would only allow about 17mA to flow. The data sheet doesn't give a minimum current but it might be marginal - you should test on the bench before you get too far. And note that the success of switching with a low input current may depend on the output current.
The upper limit of 18V, if presented to the car battery, would wreck the battery as soon as it was fully charged. A more realistic upper limit is 14.4V, which we could round up to 15V. At the lower end, I'd be surprised to see less than around 10V even when cranking, if the battery is good. So you might find a resitor that would serve your purposes.
As for the GPIO, you could set it as an input with a pull-up resistor and use the opto-coupler to switch to 0V.
Car electronics get interesting because of the voltage ranges, as you've rightly spotted. I recommend from experience that you test everything under realistic conditions before making it too inaccessible.