Can you use Digital In as a button press indicator?

07 Dec 2011

Hi All,

I've looked for this but did not find anything. Please excuse my lack of understanding of Digital In.

I was thinking that Digital In is similar to Digital Out where the signal is either On or Off. So I was wondering if you can read a digital in signal and it would show On or Off...

What I'm trying to do is this... Press a button and it supplies ?Voltage to the DigitalIn pin. The read would return "On". Depress the button and the voltage on the pin is pulled down. Now a read on that pin is "Off".

Can this be done? I did not want to hurt my mbed by trying this before asking...

Cheers

Tim

07 Dec 2011

Hi Tim

You've pretty much hit the nail on the head. DigitalIn.read() returns 0 if the pin is low and 1 if the pin is high. If you tie the pin to ground through a resistor, and up to Vout through your button, then reading the pin will return 1 when it is pressed and 0 when it isn't.

DigitalIn myButton(p20);

while(1) {
    if(myButton) ...
}

You may also want to take a look at InterruptIn, so you don't have to continuously poll the button.

Hope that helps!

Nathan

07 Dec 2011

You find a very good example in http://mbed.org/cookbook/Course-Notes in the part digital in. And a lot more good things for starting with mbed.