2016년 5월 19일 목요일

Raspberry Pi - GPIO input test with Button

Let's turn on LED when a button is pushed. Before the test, wiringPi must be installed.

The test circuit is shown as in figure. one leg of button is connect to 5V output pin and another leg is connect to #1 pin of GPIO and 10k pull-down resistor is used to prevent floating state.  In order to monitor button state, LED is used.

※ Be careful!!. If LED is connected to reverse polarity, it will be broken. Long leg is positive(+) and short leg is negative(-).

Component
  • Raspberry Pi 2 Model B
  • Push Button
  • LED(Operating Voltage: 1.8V ~ 2.3V)
  • Resistor 250Ω, 10k 


In order to test, make a simple code which is buttonTest.c

#include <wiringPi.h>

#define LED 4
#define BUTTON 1

int main(void)
{
  if(wiringPiSetup() == -1)
    return 1;

  pinMode(LED, OUTPUT);
  pinMode(BUTTON, INPUT);

  digitalWrite(LED, 0);
  int input = 0;

  for(;;)
  {
    if(digitalRead(BUTTON))
      digitalWrite(LED, 1);
    else
      digitalWrite(LED, 0); 

    delay(100);
  }

  return 0;
}

Compile and run the program.

pi@raspberrypi ~$ gcc -o buttonTest buttonTest.c -lwiringPi
pi@raspberrypi ~$ sudo ./buttonTest

When the button is pushed, LED will be turned on.

0 개의 댓글:

댓글 쓰기