Measuring Switch State using PIC

digital-logiclogic-levelpicswitches

What is the best way to measure the state of a latching switch using a micro controller?
Keeping in mind the voltage level of the input to the switch is higher then the maximum voltage input to a MCU as show below:
enter image description here

I have attempted to solve this myself using the following circuit (a simple voltage divider) however i'm not entirely confident in my solution due to my lack of experience. Below is my attempt however I am worried that when switch is open the input appears to be floating, which could yield some incorrect reading?enter image description here

Best Answer

This will work. When the switch is open, the pin does not float, it is pulled down via R2. A couple of caveats, however.

  1. You need to ensure that the ground of the MCU is connected to the ground of the 12V supply.

  2. The motor is an inductive load, and as such you will get voltage spikes when it is switched off. To counteract this you should clamp the input to the MCU to its voltage rails (0V & 5V for example) using diodes - one with the anode at the MCU input pin and the cathode at the positive MCU supply and one with the anode at ground and the cathode at the MCU pin.