simulate this circuit – Schematic created using CircuitLab
Figure 1. Redrawn schematic. "Chassis" symbol used to differentiate between isolated grounds.
- Off state: V=IR = 1mA * 4K = 4 volt across resistor.
- On state : V=IR = 5mA * 4K = 20 volt across resistor.
Is that right?
But then what is [the] internal voltage drop 5 V or less?
The sensor needs some power to operate. I steals a minimum of 1 mA from the circuit and its internal voltage regulator will drop a minimum of 5 V across it.
In [the] off state the resistor would have voltage drop of 4 V which means sensor will have 20 V [of] internal drop voltage. This will fry it?
No. It is designed to work correctly in this mode.
You can simplify your circuit by driving the opto-isolator directly from the sensor. This is done in most PLCs and has the advantage that you don't have any active circuitry on the "outside" other than the sensor. If you accidentally apply an incorrect voltage only the opto-isolator gets damaged.
The next simplification is to see if you can get rid of the Schmitt trigger. I've shown this on the logic side and you can still use it if you want. It's an unneeded complexity though as most micro's GPIOs have built-in Schmitt triggers.
Now your problem becomes that of finding the correct value for R3. The voltage at GPIO will be a function of IL1, the CTR (current transfer ratio) of the opto-isolator and the value of R3.
From the comments:
Does that NPN transistor work as a high side switch? – Dejvid_no1
With only two wires the switch knows nothing about the supply and the load since it has nothing to reference against. It can't tell the difference between being wired with a common positive 24 V or a common negative GND.
What made me confused is that "5 V or less drop" while it can go up to "20 V" when it's in the off state .. thank you for the advice.. im (sic) having 3v3 rail from the 24v rail by switching regulator non-isolated so i dont (sic) need to isolate ground right ?
If you don't need isolation then you don't need an opto-isolator.
simulate this circuit
Figure 2. Since opto-isolation is not required it can be omitted.
I've chosen the divider ratio to make the maths easy. At 20 V out from the switch the 17k and 3k resistors give a 20:3 divider giving you 3 V on the GPIO input. This gives a little safety if the output is a bit higher than 20 V.