티스토리 뷰

OS/Raspberry Pi

RaspberryPI - GPIO로 LED 켜고 끄기

파란크리스마스 2015. 8. 13. 23:55
728x90

출처 : Simple project to allow turning on/off of an LED via GPIO pin #17.
라즈베리 파이 GPIO 제어 (CONSOLE, PYTHON)
raspberry-pi4j-samples
RPi Low-level peripherals
[라즈베리파이 중급] (6) WiringPi 설치 & 깜빡이는 LED

GPIO Led 연결하기

이미지 출처 : Simple project to allow turning on/off of an LED via GPIO pin #17.


Console 에서 LED 켜고 끄기

/sys/class/gpio 폴더로 이동

$ sudo su
# cd /sys/class/gpio
# ls -l
total 0
-rwxrwx--- 1 root gpio 4096 Jan  1  1970 export
lrwxrwxrwx 1 root gpio    0 Jan  1  1970 gpiochip0 -> ../../devices/platform/soc/20200000.gpio/gpio/gpiochip0
-rwxrwx--- 1 root gpio 4096 Jan  1  1970 unexport

GPIO17 핀 초기화

심볼릭 링크가 걸린 gpio17 폴더가 생성된 것을 확인 할 수 있음

# echo 17 > /sys/class/gpio/export
# ls -l
total 0
-rwxrwx--- 1 root gpio 4096 Aug 13 05:22 export
lrwxrwxrwx 1 root gpio    0 Aug 13 05:22 gpio17 -> ../../devices/platform/soc/20200000.gpio/gpio/gpio17
lrwxrwxrwx 1 root gpio    0 Jan  1  1970 gpiochip0 -> ../../devices/platform/soc/20200000.gpio/gpio/gpiochip0
-rwxrwx--- 1 root gpio 4096 Jan  1  1970 unexport

input/output 모드 설정

# echo out > /sys/class/gpio/gpio17/direction

LED 켜기

# echo 1 > /sys/class/gpio/gpio17/value

LED 끄기

# echo 0 > /sys/class/gpio/gpio17/value

GPIO17 핀 반환

# cd /sys/class/gpio
# echo 17 > /sys/class/gpio/unexport
# ls -l
total 0
-rwxrwx--- 1 root gpio 4096 Aug 13 06:27 export
lrwxrwxrwx 1 root gpio    0 Jan  1  1970 gpiochip0 -> ../../devices/platform/soc/20200000.gpio/gpio/gpiochip0
-rwxrwx--- 1 root gpio 4096 Aug 13 06:46 unexport

java로 LED 켜고 끄기

pi4j 라이브러리 다운로드, 압축해제, 경로 이동

$ wget http://get.pi4j.com/download/pi4j-1.0.zip
$ unzip pi4j-1.0.zip 
$ cd pi4j-1.0/examples

컴파일

$ javac -cp ../lib/pi4j-core.jar ControlGpioExample.java

실행

$ sudo java -cp .:../lib/pi4j-core.jar ControlGpioExample
<--Pi4J--> GPIO Control Example ... started.
--> GPIO state should be: ON
--> GPIO state should be: OFF
--> GPIO state should be: ON
--> GPIO state should be: OFF
--> GPIO state should be: ON for only 1 second

ControlGpioExample.java 소스

// START SNIPPET: control-gpio-snippet

/*
 * #%L
 * **********************************************************************
 * ORGANIZATION  :  Pi4J
 * PROJECT       :  Pi4J :: Java Examples
 * FILENAME      :  ControlGpioExample.java  
 * 
 * This file is part of the Pi4J project. More information about 
 * this project can be found here:  http://www.pi4j.com/
 * **********************************************************************
 * %%
 * Copyright (C) 2012 - 2015 Pi4J
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * .
 * #L%
 */

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;

/**
 * This example code demonstrates how to perform simple state
 * control of a GPIO pin on the Raspberry Pi.  
 * 
 * @author Robert Savage
 */
public class ControlGpioExample {
    
    public static void main(String[] args) throws InterruptedException {
        
        System.out.println("<--Pi4J--> GPIO Control Example ... started.");
        
        // create gpio controller
        final GpioController gpio = GpioFactory.getInstance();
        
        // provision gpio pin #01 as an output pin and turn on
        final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "MyLED", PinState.HIGH);

        // set shutdown state for this pin
        pin.setShutdownOptions(true, PinState.LOW);

        System.out.println("--> GPIO state should be: ON");

        Thread.sleep(5000);
        
        // turn off gpio pin #01
        pin.low();
        System.out.println("--> GPIO state should be: OFF");

        Thread.sleep(5000);

        // toggle the current state of gpio pin #01 (should turn on)
        pin.toggle();
        System.out.println("--> GPIO state should be: ON");

        Thread.sleep(5000);

        // toggle the current state of gpio pin #01  (should turn off)
        pin.toggle();
        System.out.println("--> GPIO state should be: OFF");
        
        Thread.sleep(5000);

        // turn on gpio pin #01 for 1 second and then off
        System.out.println("--> GPIO state should be: ON for only 1 second");
        pin.pulse(1000, true); // set second argument to 'true' use a blocking call
        
        // stop all GPIO activity/threads by shutting down the GPIO controller
        // (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
        gpio.shutdown();
    }
}
//END SNIPPET: control-gpio-snippet

raspberry-pi4j-samples 의 Relay02.java 예제 사용하기

Relay02.java 예제는 핀번호를 인자로 실행해서 Command 입력으로 LED를 켜고 끄기가 가능함

raspberry-pi4j-samples 다운로드, 경로이동, 컴파일, 실행

$ git clone https://code.google.com/p/raspberry-pi4j-samples/
$ cd raspberry-pi4j-samples/Relay/src
$ javac -cp ~/pi4j-1.0/lib/pi4j-core.jar relay/Relay02.java
$ sudo java -cp .:../../../pi4j-1.0/lib/pi4j-core.jar relay.Relay02 0 
GPIO Control - pin 0... started.
--> GPIO state is Low
Type Q to quit.
So? > 1
Setting pin to high
--> GPIO state is High
So? > 0
Setting pin to low
--> GPIO state is Low
So? > q

Relay02.java 소스

package relay;

import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.Pin;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * 5v are required to drive the relay
 * The GPIO pins deliver 3.3v
 * To drive a relay, a relay board is required.
 * (it may contain what's needed to drive the relay with 3.3v)
 */
public class Relay02
{
  private static Pin relayPin = RaspiPin.GPIO_00;
  
  public static void main(String[] args) throws InterruptedException
  {
    int pin = 0;
    if (args.length > 0)
    {
      try 
      {
        pin = Integer.parseInt(args[0]);
      }
      catch (NumberFormatException nfe)
      {
        nfe.printStackTrace();
      }
      switch (pin)
      {
        case 0:
          relayPin = RaspiPin.GPIO_00;
          break;
        case 1:
          relayPin = RaspiPin.GPIO_01;
          break;
        case 2:
          relayPin = RaspiPin.GPIO_02;
          break;
        case 3:
          relayPin = RaspiPin.GPIO_03;
          break;
        case 4:
          relayPin = RaspiPin.GPIO_04;
          break;
        case 5:
          relayPin = RaspiPin.GPIO_05;
          break;
        case 6:
          relayPin = RaspiPin.GPIO_06;
          break;
        case 7:
          relayPin = RaspiPin.GPIO_07;
          break;
        case 8:
          relayPin = RaspiPin.GPIO_08;
          break;
        case 9:
          relayPin = RaspiPin.GPIO_09;
          break;
        case 10:
          relayPin = RaspiPin.GPIO_10;
          break;
        case 11:
          relayPin = RaspiPin.GPIO_11;
          break;
        case 12:
          relayPin = RaspiPin.GPIO_12;
          break;
        case 13:
          relayPin = RaspiPin.GPIO_13;
          break;
        case 14:
          relayPin = RaspiPin.GPIO_14;
          break;
        case 15:
          relayPin = RaspiPin.GPIO_15;
          break;
        case 16:
          relayPin = RaspiPin.GPIO_16;
          break;
        case 17:
          relayPin = RaspiPin.GPIO_17;
          break;
        case 18:
          relayPin = RaspiPin.GPIO_18;
          break;
        case 19:
          relayPin = RaspiPin.GPIO_19;
          break;
        case 20:
          relayPin = RaspiPin.GPIO_20;
          break;
        default: // Model a+ and B+ go up to 30
          System.out.println("Unknown GPIO pin [" + pin + "], must be between 0 & 20.");
          System.out.println("Defaulting GPIO_00");
          break;
      }
    }
    System.out.println("GPIO Control - pin " + pin + "... started.");

    // create gpio controller
    final GpioController gpio = GpioFactory.getInstance();

    // For a relay it seems that HIGH means NC (Normally Closed)...
    final GpioPinDigitalOutput outputPin = gpio.provisionDigitalOutputPin(relayPin); //, PinState.HIGH);

    System.out.println("--> GPIO state is " + (outputPin.isHigh()?"High":"Low"));
    
    boolean go = true;
    
    System.out.println("Type Q to quit.");
    while (go)
    {
      String user = userInput("So? > ");
      if ("Q".equalsIgnoreCase(user))
        go = false;
      else
      {
        int val = 0;
        try
        {
          val = Integer.parseInt(user);
          if (val != 0 && val != 1)
            System.out.println("Only 1 or 0, please");
          else
          {
            System.out.println("Setting pin to " + (val == 1 ? "high" : "low"));
            if (val == 0)
              outputPin.low();
            else
              outputPin.high();
            System.out.println("--> GPIO state is " + (outputPin.isHigh()?"High":"Low"));
          }
        }
        catch (NumberFormatException nfe)
        {
          nfe.printStackTrace();
        }
      }
    }
    gpio.shutdown();
  }

private static final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));

  public static String userInput(String prompt)
  {
    String retString = "";
    System.err.print(prompt);
    try
    {
      retString = stdin.readLine();
    }
    catch(Exception e)
    {
      System.out.println(e);
      String s;
      try
      {
        s = userInput("<Oooch/>");
      }
      catch(Exception exception) 
      {
        exception.printStackTrace();
      }
    }
    return retString;
  }
}

댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
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
글 보관함