# Detecting 12V using MCU

I am trying to detect a 12V input signal coming in from a DC wall charger using an STM8 microcontroller. I am using a voltage divider with 10k/2.2k : First there is a 10K resistor in series with the 12V signal.

Then there is a voltage divider after which it is fed into an AIN pin of the MCU.

But the issue I am facing is that when the power supply to the 12V charger is switched off, it immediately drops to 9V but then the capacitors inside the charger discharge slowly and it takes almost a minute for my current code to detect the loss of 12V signal. Here is my code :

while(1){

if (analogValue < 600) {
GPIO_WriteLow(LED1_GPIO_PORT, LED1_GPIO_PIN);
GPIO_WriteHigh(LED2_GPIO_PORT, LED2_GPIO_PIN);
GPIO_WriteLow(MOSFET_GPIO_PORT, MOSFET_GPIO_PIN);
}

else {

GPIO_WriteHigh(LED1_GPIO_PORT, LED1_GPIO_PIN);
GPIO_WriteLow(LED2_GPIO_PORT, LED2_GPIO_PIN);
GPIO_WriteHigh(MOSFET_GPIO_PORT, MOSFET_GPIO_PIN);
}

}


What can I do to make this detection instantaneous? I have also tried putting in a 470nf Cap on the input 12V to little effect.

• What logic levels do the MCU use? 5V or 3.3V? 20k over 2k2 gives 1.189V which doesn't make a whole lot of sense either way. Commented Jun 28 at 13:07
• I use an STM8, so its 3.3V Commented Jul 1 at 13:40
• Then you need to fix the voltage divider so that you get 3.3V, because this is plain wrong. 20k over 7k5 gives 3.273V and those are standard E series resistor values. Commented Jul 1 at 13:46

You could improve your interface circuit to solve the problem at source. Might want a bit of experimenting, but for instance:

simulate this circuit – Schematic created using CircuitLab

Assuming that your uC is running on 3V3, the logic level should switch as soon as the 12V drops to about 10V. The signal diode is needed to stop the pin voltage going negative.

you could use an optocoupler if you want to detect the signal and also it is bad for mcu pin to give it direct 12v . just use out from opto coupler and detect it with mcu with pullup .

Use a zener diode to drop the first 9V of input and then derive the input from the remainder. I can not give you exact numbers for the voltage divider because I dont know your microcontroller thresholds.

simulate this circuit – Schematic created using CircuitLab

a voltage supervisor like TL7712 or an adjustable reference like TL7431