Interfacing switches with microcontroller

microcontrollermicroprocessor

Im trying to interface momentary push-button switches to my Stellaris EK-LM4F120XL.

Im using a positive logic interface, to momentarily set pin as HIGH if the button is pressed. A 10K resistor is connected to GND from the switch, which is then connected to Vcc, 5V. The selected pin is connected to this junction, setting the pin as LOW when no current flows and a 0V signal is at the pin. Then when current flows the voltage at the pin is Vcc and is set HIGH.

Using a multimeter this works flawlessly.. Although, when debugging – the output isnt triggered as desired..

My activation code in main is as follows..

if ((GPIOX_DATA & 0xXX) == 1) // IF THE PORTS' DATA REGISTER, AT PIN, IS HIGH,
    GPIOX_DATA |= 0xXX;       // SET THIS PORTS' DATA REGISTER, AT PIN, TO HIGH

(The control of setting the pin via the data-register works fine, eg on-board LEDs..)

It is my understanding that you cannot write to an input pin – therefore its value is set by its logic-level. If it has a threshold voltage similar to TTL or CMOS, the active 5V on the pin should be setting it as HIGH – therefore == 1.

My init code sets the input pin as –
DIR as input
AFSEL to regular
DEN to digital..

Ive even tried adding disable analog thru AMSEL, clear port control thru PCTL..
Just to test the control, I want to turn on an on-board LED while button is depressed..

Am I missing something..?

Best Answer

When examining a single bit in a byte (or register) using & it's important to remember that the result of the & will be a masked value, not the value of the bit you're interested in.

For example, if you have the value 0b10110101 in a register and you want to examine bit 2, you could mask it out with 0b00000100:

0b10110101
0b00000100 &
==========
0b00000100 = 4

So the result is, in decimal, 4. In your if statement you are comparing the results of the & operation with 1. That can only ever be true if you happen to be examining bit 0 in your register.

If you change your comparison either so it's comparing the masked value to the value of the mask then it can become true for the value you're actually examining.

Better still, drop the comparison altogether:

if (GPIOX_DATA & 0xXX) // IF THE PORTS' DATA REGISTER, AT PIN, IS HIGH,
    GPIOX_DATA |= 0xXX;       // SET THIS PORTS' DATA REGISTER, AT PIN, TO HIGH

In an if comparison you're only interested in a true or false state. In C a false state is defined as 0, and a true state is defined as any other value but 0. So say the equation GPIOX_DATA & 0xXX results in 4, that is a true value, since it's not 0.