I have a device providing a signal of either +9v or +5v (depending on some action on the device) plus a GND. I would like to convert the Vin signal into something readable as a digital 1 or 0 on CMOS 3.3v levels, so I can know from a microcontroller when the action is happening. Ideally, with common components available without needing to get out of home. I've tried with a voltage divider (to convert 9v/5v to 4.5v/2.5v for example) and then a couple of diodes to reduce the divided voltage in 1.4v so I get 3.1v/1.1v, but after some tests I don't get what it's expected. Thanks in advance
Try simulating the above schematic. The R1/R2 voltage divider will reduce the signal that is either 5V or 9V to a lower voltage.
9V –> 3.5V @ VA
5V –> 1.9V @ VA
So when it is 9V the 9V will bias the R1/R2 so that VA is higher than Q1 emitter and Q1 will be off. When it is 5V it will allow VA to lower, turning on Q1. There is about 76uA coming from R3 into VA but it's impact is small compared to about 1mA of bias through R1/R2. While not super-precise, it does do the job with only a few simple components. If whatever PNP transistor you have doesn't have enough gain, ie. doesn't fully switch on, you can increase R4 to 3k3.
One possible way to do this is to use a voltage divider to provide a 1.5V reference point ( about half of 3.3V). Then use a comparator to compare input to this reference point. Since 9V/5V is too large, we can use another voltage divider to provide a suitable voltage. Take the midpoint of the 9V and 5V, ie 7V as the point you’d like to distinguish 9V and 5V levels. Create voltage divider to create a 1.5V voltage if the input was 7V. As an example 2.2k and 8.2K divider would provide almost 1.5V. Now if Vin is 5V the voltage after divider would be 1V and if input was 9V then voltage after divider would be 1.9V. Using a 3.3V Voltage source for comparator would give 0V and 3.3V output levels.