Filter results by

Reading a Button

In the previous tutorial we used the ARTIK GPIOs to blink an LED, demonstrating controlling a digital output. Now, we'll set up a GPIO as a digital input and use that to read the position of a pushbutton switch.

Hardware Required

Here's what you'll need to run this tutorial:

  • ARTIK 5, 7, or 10 developer board
  • LED
  • 220 ohm resistor
  • Momentary button or Switch
  • Breadboard and connector wires

Building the Circuit

ARTIK 7 Board. The ARTIK 7 developer kit makes this tutorial easy, as the board implements a switch circuit already. You don't have to connect anything. But if you do want to construct the external circuit for educational purposes, please do so! Follow the directions below. You'll need it if you want to try the Arduino IDE later in this tutorial.

ARTIK 5 or 10 Board. We're choosing arbitrarily to use GPIO pin [2] for the ARTIK 5 or 10 board. Build the circuit as shown.

Circuit for reading a button

Schematic

Note that the LED is only an indicator. It is not controlled by a digital output. (However, you are welcome to implement that on your own as another project.)

When the button is open (unpressed), there is no connection between the two legs of the pushbutton, so the pin is connected to ground and the digital input reads LOW. The LED is off. When the button is pressed, it makes a connection between the two legs, connecting the pin to 5 volts, so that the digital input is presented with a HIGH signal. The LED turns on because it's now getting powered.

Reading the Button Manually

As in the previous tutorial, we will use the Linux® sysfs mechanism to "export" control of a pin.

ARTIK 7 Board

Our goal is to read an on-board switch, mapped as

  • sysfs GPIO 30 for SW403 (next to board edge, alongside Red LED)
  • sysfs GPIO 32 for SW404 (alongside Blue LED)

(click here to see what external GPIO pins you could map to instead)

ARTIK 7 Example. For our example, let's pick the switch next to the board edge.

  1. Request control of the desired GPIO.

    $ echo 30 > /sys/class/gpio/export

  2. Configure the GPIO to be an input.

    $ echo in > /sys/class/gpio/gpio30/direction

  3. Read its value.

    $ cat /sys/class/gpio/gpio30/value

    Try this last step repeatedly, with the button alternately depressed and released, to see the difference in the return value.

ARTIK 5/10 Board

Our goal is to read GPIO pin [2], mapped as

(click on the links above to see where this mapping comes from)

So if working with an ARTIK 5 board, you would proceed as follows.

  1. Request control of the desired GPIO.

    $ echo 121 > /sys/class/gpio/export

  2. Configure the GPIO to be an input.

    $ echo in > /sys/class/gpio/gpio121/direction

  3. Read its value.

    $ cat /sys/class/gpio/gpio121/value

    Try this last step repeatedly, with the button alternately depressed and released, to see the difference in the return value.

Using the Arduino IDE

Here's the Arduino code for reading a button, which must be connected to physical pin [2].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const int buttonPin = 2; // the number of the pushbutton pin

int buttonState = 0;     // variable for reading the pushbutton status

void setup() {
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  Serial.print("buttonState = ");
  Serial.println(buttonState);

  delay(1000);
}

Using Python

In this version of the example, we configure the pin using Python code.

Use the code below for ARTIK 10. The same code works for ARTIK 5 with buttonpin = 121 or for ARTIK 7 with buttonpin = 30. Notice how closely the code follows the manual method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#!/usr/bin/python

import time
import sys

print "Toggle a button"
buttonpin = 8

#export pin 8 by opening file and writing the pin number to it
pinctl = open("/sys/class/gpio/export", "wb", 0)
try:
    pinctl.write( str(buttonpin))
    print "Exported pin", str(buttonpin)
except:
    print "Pin ", str(buttonpin), " has been exported"
pinctl.close()

#set pin to be digital input
filename = '/sys/class/gpio/gpio%d/direction' % buttonpin
pinctldir = open(filename, "wb", 0)
try:
    pinctldir.write("in")
    print "Set pin ", str(buttonpin), " as digital input"
except:
    print "Failed to set pin direction"
pinctldir.close()

def exit_gpio():
    #unexport pin
    pinctl = open("/sys/class/gpio/unexport", "wb", 0)
    try:
        pinctl.write( str(buttonpin))
        print "Unexported pin", str(buttonpin)
    except:
        print "Pin ", str(buttonpin), " has been unexported"
    pinctl.close()

#pin value changes when the button is pressed
filename = '/sys/class/gpio/gpio%d/value' % buttonpin
while True:
    try:
        pin = open(filename, "rb", 0)
        print pin.read()
        time.sleep(1)
        pin.close()
    except KeyboardInterrupt:
        exit_gpio()
        sys.exit(0)

To load and run this code:

  1. Paste the code into a file named button.py on your local system, changing the buttonpin value as needed.

  2. Copy it over using a program like scp . For example:
    $ scp button.py 128.106.24.0:/.
    (The example shown works from a bash command window on the local system, not from the ARTIK terminal.)

  3. Type python –i button.py to execute the code on ARTIK.

You could also have copied the code from your host system text editor and pasted it into vi on the ARTIK terminal window. But you'll probably want to search for and install a bash command window utility on your host system – you'll find scp really handy going forward!

Using C

To read button state with C code, we need to include the digitalRead() function listed here. Again, we are using the sysfs interface exported by the Linux kernel to access these GPIO pins.

You can find the source code here for ARTIK 10. You can use the same code for ARTIK 5 or 7, but you will need to define your inputPin to be 121 or 30 (respectively).

Transfer the code to the ARTIK and compile and run as usual!

Last updated on: