7 years, 10 months ago.

How to check if a pin is high or low

Hello, I am very very new to this world and I ran into a problem.

I need to see whenever there is a voltage (preferably after +4.0 V) on a pin. The problem is, when I declare the pin as DigitalIn, the pin always have 3.3v and unless I ground it, it always gives 1. I need the opposite. I need the pin to give 0 as default but 1 whenever I connect it to a voltage source.

Any help is much appreciated, thanks.

1 Answer

7 years, 10 months ago.

Hello Alper,

You can select the preferred PinMode by passing a second argument to the constructor as below:

DigitalIn  digitalIn(D2, PullNone);

Or you can change the PinMode using the mode method:

#include "mbed.h"
/...
DigitalIn  digitalIn(D2);
/...
int main()
{
/...
    digitalIn.mode(PullNone);
/...
}

See the mbed documentation for more info.

PinMode for the FRDM-KL25 board is defined in the mbed-os-5.8.5\targets\TARGET_Freescale\TARGET_KLXX\TARGET_KL25Z\PinNames.h file as follows:

/* PullDown not available for KL25 */
typedef enum {
    PullNone = 0,
    PullUp = 2,
    PullDefault = PullUp
} PinMode;

Unfortunately PullDown (connects an internal resistor between the input pin and ground to keep the input voltage level at 0V (ground) when no external voltage is applied) is not available for the KL25 board. So try to use PullNone. If it doesn't work then connect an external 4k7 resistor between the input pin and ground.

Warning

To avoid board damage do not apply a voltage higher than +3.3V to an input pin!

For the KL25 the maximum input on an input pin is VDD + 0.3 V which means you can go a tiny bit over 3.3 V but certainly not up to 4 V.

An input is guarantee to be counted as high at 0.7 * Vdd or around 2.25 V (the threshold will normally be closer to 0.5 * Vdd but it can depend on other factors) . So if you wire it up as:

Signal - 20k - input pin - 33k - Ground

Then you'll be save with input voltages up to 5 V with anything over 3.6 V counting as a high input and not connected showing up as a low input. Exact values of the resistors don't matter as long as you keep the ratio correct, you could probably vary them by a factor of 10 each way without any problems.

posted by Andy A 31 May 2018