728x90

출처 : rpi_HC-SR501/src/main/java/org/jboss/summit2015/hcsr501/MotionSensor.java

pi4j 다운로드

$ mkdir pi4j
$ cd pi4j
$ wget http://get.pi4j.com/download/pi4j-1.0.zip
--2016-07-09 16:59:31--  http://get.pi4j.com/download/pi4j-1.0.zip
Resolving get.pi4j.com (get.pi4j.com)... 54.231.114.185
Connecting to get.pi4j.com (get.pi4j.com)|54.231.114.185|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 3807428 (3.6M) [application/zip]
Saving to: ‘pi4j-1.0.zip.1’
 
pi4j-1.0.zip.1      100%[=====================>]   3.63M   544KB/s   in 6.4s   
 
2016-07-09 16:59:38 (581 KB/s) - ‘pi4j-1.0.zip.1’ saved [3807428/3807428]
 
$ unzip pi4j-1.0.zip 

핀 배치

MotionSensor.java

import com.pi4j.io.gpio.*;
import com.pi4j.io.gpio.trigger.GpioCallbackTrigger;

import java.util.concurrent.Callable;

/**
 * Use the pi4j classes to watch a gpio trigger. This uses the pin number scheme as outlined in:
 * http://pi4j.com/pins/model-2b-rev1.html
 */
public class MotionSensor {
    public static void main(String[] args) throws InterruptedException {

        System.out.printf("PIR Module Test (CTRL+C to exit)\n");

        // create gpio controller
        final GpioController gpio = GpioFactory.getInstance();
        // provision gpio pin #29, (header pin 40) as an input pin with its internal pull down resistor enabled
        final GpioPinDigitalInput pir = gpio.provisionDigitalInputPin(RaspiPin.GPIO_29);
        System.out.printf("Ready\n");

        // create a gpio callback trigger on the gpio pin
        Callable<Void> callback = () -> {
            System.out.println(" --> GPIO TRIGGER CALLBACK RECEIVED ");
            return null;
        };
        // create a gpio callback trigger on the PIR device pin for when it's state goes high
        pir.addTrigger(new GpioCallbackTrigger(PinState.HIGH, callback));

        // stop all GPIO activity/threads by shutting down the GPIO controller
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.out.println("Interrupted, stopping...\n");
                gpio.shutdown();
            }
        });

        // keep program running until user aborts (CTRL-C)
        for (;;) {
            Thread.sleep(100);
        }

    }
}

컴파일

$ javac -cp pi4j-1.0/lib/pi4j-core.jar MotionSensor.java 

실행

$ sudo java -cp .:pi4j-1.0/lib/pi4j-core.jar MotionSensor
PIR Module Test (CTRL+C to exit)
Ready
 --> GPIO TRIGGER CALLBACK RECEIVED 
 --> GPIO TRIGGER CALLBACK RECEIVED 
^CInterrupted, stopping...

GPIO 핀 배열

728x90
728x90

/etc/rc.local 파일  rc.local

#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

# Print the IP address
_IP=$(hostname -I) || true
if [ "$_IP" ]; then
  printf "My IP address is %s\n" "$_IP"
fi

exit 0

/etc/network/interfaces 파일  interfaces

# interfaces(5) file used by ifup(8) and ifdown(8)

# Please note that this file is written to be used with dhcpcd
# For static IP, consult /etc/dhcpcd.conf and 'man dhcpcd.conf'

# Include files from /etc/network/interfaces.d:
source-directory /etc/network/interfaces.d

auto lo
iface lo inet loopback

iface eth0 inet manual

allow-hotplug wlan0
iface wlan0 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

allow-hotplug wlan1
iface wlan1 inet manual
    wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf

/etc/wpa_supplicant/wpa_supplicant.conf 파일  wpa_supplicant.conf

country=GB
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1

펌웨어 업그레이드

$ sudo BRANCH=next rpi-update
$ sudo shutdown -r now

WIFI 자동연결 설정

출처 : Setting up WiFi connection

$ sudo vi /etc/network/interfaces

내용 추가

auto wlan0

WIFI 절약모드 끄기

$ sudo iwconfig wlan0 power off

서비스 비활성화

$ sudo update-rc.d nginx disable
$ sudo update-rc.d supervisor disable
728x90
728x90

출처 : Download & Install - WiringPi
라즈베리파이 GPIO 강좌 : 04. Output 테스트 (LED 출력, C언어)

라즈베리파이 업데이트, 업그레이드

$ sudo apt-get update
$ sudo apt-get upgrade

소스관리툴 git 다운로드

$ sudo apt-get install git-core

wiringPi 소스 다운로드

git clone git://git.drogon.net/wiringPi

wiringPi 컴파일

$ ./build

wiringPi 설치확인

$ gpio -v gpio readall
gpio version: 2.32
Copyright (c) 2012-2015 Gordon Henderson
This is free software with ABSOLUTELY NO WARRANTY.
For details type: gpio -warranty
 
Raspberry Pi Details:
  Type: Pi 2, Revision: 01, Memory: 1024MB, Maker: Sony 
  * Device tree is enabled.
  * This Raspberry Pi supports user-level GPIO access.
    -> See the man-page for more details
    -> ie. export WIRINGPI_GPIOMEM=1

LDE 제어하기

소스 작성

$ vi led.c
#include 
#include 

#define LED1 28 // BCM_GPIO 20
#define LED2 29 // BCM_GPIO 21

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

  pinMode (LED1, OUTPUT) ;
  pinMode (LED2, OUTPUT) ;

  for (;;)
  {
    digitalWrite (LED1, 1) ; // On
    digitalWrite (LED2, 1) ; // On

    delay (1000) ; // ms

    digitalWrite (LED1, 0) ; // Off
    digitalWrite (LED2, 0) ; // Off

    delay (1000) ;
  }
  return 0 ;
}

컴파일

$ gcc -o led led.c -lwiringPi

실행

$ sudo ./led

실행 결과

728x90
728x90

출처 : Serial Communication in Java with Raspberry Pi and RXTX
HowTo: Serial connection to Raspberry Pi (Java, RXTX, UART)
How to Use RXTX on Raspberry Pi or BeagleBone
Ryanteck Raspberry Pi Serial Debug Clip review
Raspberry Pi and the Serial Port
Raspberry Pi UART serial wont work
Using the UART
Raspberry Pi Serial Communication: What, Why, and a Touch of How
RPi Serial Connection


핀맵

적색 - 5V
백색 - TXD
녹색 - RXD
흑색 - GND

bluetooth 장착 확인

$ lsusb | grep -i bluetooth
Bus 001 Device 006: ID 0a12:0001 Cambridge Silicon Radio, Ltd Bluetooth Dongle (HCI mode)

서비스 설치

$ sudo apt-get install --no-install-recommends bluetooth

서비스 실행 확인

$ sudo service bluetooth status
bluetooth is running.

-

블루투스 serial 부팅

출처 : A cheap Bluetooth serial port for your Raspberry Pi

기본적으로 라즈베리 파이는 직렬 포트로 부팅 할 때 부팅 메시지를 기록하고. 또한에 로그인 콘솔을 시작합니다. 

라즈베리파이는 직렬 포트로 사용하는 기본 전송 속도는 115200 BPS 이지만 블루투스 모듈은 공장에서 9600 BPS로 되어 라즈베리파이의 전송속도를 9600 BPS로 설정해야 됩니다.

RPi의 Serial port의 기본 전송 속도 확인 (/boot/cmdline.txt, /etc/inittab)

$ cat /boot/cmdline.txt
dwc_otg.lpm_enable=0 console=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p6 rootfstype=ext4 elevator=deadline rootwait
$ cat /etc/inittab

.. 생략 ...

#Spawn a getty on Raspberry Pi serial line
T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100

RPi의 Serial port의 기본 전송 속도 변경 (/boot/cmdline.txt)

$ cd /boot
$ sudo cp cmdline.txt cmdline.bak
$ sudo vi /boot/cmdline.txt 

dwc_otg.lpm_enable=0 console=ttyAMA0,9600 console=tty1 root=/dev/mmcblk0p6 rootfstype=ext4 elevator=deadline rootwait

Kernel Debugger Boot (커널 디버깅 할때만 하세요)

dwc_otg.lpm_enable=0 console=ttyAMA0,9600 kgdboc=ttyAMA0,9600 console=tty1 root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadline rootwait

RPi의 Serial port의 기본 전송 속도 변경 (/boot/inittab)

$ sudo vi /etc/inittab 

#Spawn a getty on Raspberry Pi serial line
#T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100
T0:23:respawn:/sbin/getty -L ttyAMA0 9600 vt100

BlueCove 컴파일 하기

bluecove-gpl-2.1.0.jar

출처 : Bluecove programming problem

BlueCove 컴파일 관련 패키지 설치

$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo apt-get autoremove
$ sudo apt-get install bluetooth bluez-utils blueman
$ hcitool dev
Devices:
        hci0    00:1A:7D:DA:71:10

BlueZ 라이브러리 설치 - 컴파일시 필요

$ sudo apt-get install libbluetooth-dev

ant 설치

$ sudo apt-get install ant

BlueCove ant 빌드

$ ant all
Buildfile: /home/pi/bluecove-gpl-2.1.0/build.xml

clean:
   [delete] Deleting directory /home/pi/bluecove-gpl-2.1.0/target

init-native:
    [mkdir] Created dir: /home/pi/bluecove-gpl-2.1.0/target/classes
    [mkdir] Created dir: /home/pi/bluecove-gpl-2.1.0/target/native
     [echo] java.home /usr/lib/jvm/jdk-8-oracle-arm-vfp-hflt/jre

verify-java-home:

verify-cruisecontrol:

init:

verify-bluecove-main-exists:

compile:
     [echo] compiling on java 1.8.0
    [javac] /home/pi/bluecove-gpl-2.1.0/build.xml:87: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds
    [javac] Compiling 3 source files to /home/pi/bluecove-gpl-2.1.0/target/classes
    [javac] warning: [options] bootstrap class path not set in conjunction with -source 1.3
    [javac] warning: [options] source value 1.3 is obsolete and will be removed in a future release
    [javac] warning: [options] target value 1.1 is obsolete and will be removed in a future release
    [javac] warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
    [javac] 4 warnings

jni-headers:
     [echo] create JNI headers using java.home /usr/lib/jvm/jdk-8-oracle-arm-vfp-hflt/jre

compile-native-lib:
     [echo] compiling  .c -> .o
    [apply] /home/pi/bluecove-gpl-2.1.0/src/main/c/BlueCoveBlueZ_SDPServer.c: In function 쁞luecove_sdp_extract_pdu

                      [apply] /home/pi/bluecove-gpl-2.1.0/src/main/c/BlueCoveBlueZ_SDPServer.c:94:47: warning: assignment from incompatible pointer type [enabled by default]
     [echo] linking    .o -> libbluecove_arm.so
     [echo] ldd libbluecove_arm.so
     [exec]     /usr/lib/arm-linux-gnueabihf/libcofi_rpi.so (0x76f1d000)
     [exec]     libbluetooth.so.3 => /usr/lib/arm-linux-gnueabihf/libbluetooth.so.3 (0x76eef000)
     [exec]     libc.so.6 => /lib/arm-linux-gnueabihf/libc.so.6 (0x76dbf000)
     [exec]     /lib/ld-linux-armhf.so.3 (0x76f40000)
     [exec] 
     [exec]     Version information:
     [exec]     /usr/lib/arm-linux-gnueabihf/libcofi_rpi.so:
     [exec]             libc.so.6 (GLIBC_2.4) => /lib/arm-linux-gnueabihf/libc.so.6
     [exec]     /usr/lib/arm-linux-gnueabihf/libbluetooth.so.3:
     [exec]             ld-linux-armhf.so.3 (GLIBC_2.4) => /lib/ld-linux-armhf.so.3
     [exec]             libc.so.6 (GLIBC_2.7) => /lib/arm-linux-gnueabihf/libc.so.6
     [exec]             libc.so.6 (GLIBC_2.4) => /lib/arm-linux-gnueabihf/libc.so.6
     [exec]     /lib/arm-linux-gnueabihf/libc.so.6:
     [exec]             ld-linux-armhf.so.3 (GLIBC_2.4) => /lib/ld-linux-armhf.so.3
     [exec]             ld-linux-armhf.so.3 (GLIBC_PRIVATE) => /lib/ld-linux-armhf.so.3
     [copy] Copying 1 file to /home/pi/bluecove-gpl-2.1.0/src/main/resources
     [copy] Copying 1 file to /home/pi/bluecove-gpl-2.1.0/target/classes

native-lib:

jar:
      [jar] Building jar: /home/pi/bluecove-gpl-2.1.0/target/bluecove-gpl-2.1.0.jar

all:

BUILD SUCCESSFUL
Total time: 31 seconds
pi@raspberrypi:~/bluecove-gpl-2.1.0$ 

Sample 컴파일 및 실행

$ wget http://get.pi4j.com/download/pi4j-1.1-SNAPSHOT.zip
$ unzip pi4j-1.1-SNAPSHOT.zip
$ cp /home/pi/bluecove-gpl-2.1.0/target/bluecove-gpl-2.1.0.jar ~/pi4j-1.1-SNAPSHOT/lib
$ javac -cp lib/pi4j-core.jar:lib/bluecove-gpl-2.1.0.jar:lib/bluecove-2.1.0.jar SimpleSPPServer.java
$ sudo java -cp .:lib/pi4j-core.jar:lib/bluecove-gpl-2.1.0.jar:lib/bluecove-2.1.0.jar SimpleSPPServer
BlueCove version 2.1.0 on bluez
Address: 001A7DDA7110
Name: raspberrypi-0

Server Started. Waiting for clients to connect...


728x90
728x90

출처 : MJPG streaming with a Raspberry Pi and a webcam

산딸기 마을에서 만든 rc_car를 이동하면서 구글 Cardboard로 3D 영상을 보기 위해서
RaspberryPI 두개로 각각 PI Camera로 3D 좌우 영상을 얻어 보았지만 싱크가 맞지 않아서,
3D 영상을 얻지 못했습니다.

그래서 3D 카메라를 찾다가 AliExpress에서 USB 타입의 듀얼 카메라를 구입습니다.
PaspberryPI에서 mjpg_streamer를 두번 실행해서, html로 두개의 영상을 좌우로 구성했습니다.

구글의 Cardboard로 핸드폰 브라우져의 좌우 영상보시면 3D 영상을 보실 수 있습니다.

AliExpress에서 구입한 Camera

Camera 설치 확인

USB 방식으로 RaspberryPI에 USB에 연결만 하면 바로 설치가 됩니다.

$ ls /dev/vi*
/dev/video0  /dev/video1

Camera 1 - mjpg_streamer 실행

$ mjpg_streamer -i "input_uvc.so -d /dev/video0 -n -y -f 15 -r 640x480"

Camera 2 - mjpg_streamer 실행

$ mjpg_streamer -i "input_uvc.so -d /dev/video1 -n -y -f 15 -r 640x480" -o "output_http.so -w /usr/local/www2 -p 8081"

듀얼 화면 구성 html 소스

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">
<script type="text/javascript" src="js-mjpeg/eventemitter2.min.js"></script>
<script type="text/javascript" src="js-mjpeg/mjpegcanvas.min.js"></script>

<script type="text/javascript" type="text/javascript">
function init() {

	var canvas_width = (document.body.clientWidth / 2);
	var canvas_heigth = canvas_width * 75 / 100;
	
	// Create the main viewer.
	var viewer_l = new MJPEGCANVAS.Viewer({
	  divID : 'mjpeg_l',
	  host : '192.168.1.190',
	  port : '8080',
	  width : canvas_width,
	  height : canvas_heigth,
	  topic : '/?action=stream'
	});
	
	var viewer_r = new MJPEGCANVAS.Viewer({
	  divID : 'mjpeg_r',
	  host : '192.168.1.190',
	  port : '8081',
	  width : canvas_width,
	  height : canvas_heigth,
	  topic : '/?action=stream'
	});
}
</script>
<style type="text/css">
body {
  margin: 0;
  padding: 0;
}

.blind, body, button, dd, dl, dt, fieldset, form, canvas {
  margin: 0;
  padding: 0;
}

.grid1_wrap, .grid2_wrap {
  margin: 0;
  box-sizing: border-box;
}

@media (min-width: 640px)
.grid1_wrap.news_wrap .brick-vowel {
  width: 50%;
}

.brick-house .brick-vowel {
  float: left;
  /* width: 100%; */
}
</style>
</head>

<body onload="init()">

<div class="flick-panel" style="height: 100%; transition-property: -webkit-transform; transition-duration: 0ms; position: absolute; width: 100%; left: 0px; top: 0px; float: left;">
	<div class="grid1_wrap news_wrap brick-house" data-last="true" style="padding-left:0px">
		<div class="brick-vowel" id="mjpeg_l"></div>
		<div class="brick-vowel" id="mjpeg_r"></div>
	</div>
</div>

</body>
</html>

ie에서 듀얼 화면 확인

핸드폰 브라우져에서 듀얼 화면 확인

Google Cardboard의 프라스틱 버전에 핸드폰 설치 

728x90
728x90

출처 : Using a 16x2 LCD Display with a Raspberry Pi
LCD Display Tutorial for Raspberry Pi
Interfacing 16x2 LCD with Raspberry Pi using GPIO & Python
16×2 LCD Module Control Using Python
rasbperry pi B gpio between extention board mapping
Raspberry Pi 2 Model B GPIO 40 Pin Block Pinout
How To Use A MCP23017 I2C Port Expander With The Raspberry Pi ? Part 1

Using a 16x2 LCD Display with a Raspberry Pi

Breadboard 설치된 최종 모습

회로도

실행 - lcd.lcd_init()

$ sudo python
Python 2.7.3 (default, Mar 18 2014, 05:13:23) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.chdir('/home/pi')
>>> import lcd
>>> lcd.lcd_init()

 

실행 - Line 1 문자열 출력

$ sudo python
Python 2.7.3 (default, Mar 18 2014, 05:13:23) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.chdir('/home/pi')
>>> import lcd
>>> lcd.lcd_init()
>>> lcd.lcd_byte(lcd.LCD_LINE_1, lcd.LCD_CMD)
>>> lcd.lcd_string("Raspberry PI", 2)

 

실행 - Line 2 문자열 출력

$ sudo python
Python 2.7.3 (default, Mar 18 2014, 05:13:23) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.chdir('/home/pi')
>>> import lcd
>>> lcd.lcd_init()
>>> lcd.lcd_byte(lcd.LCD_LINE_1, lcd.LCD_CMD)
>>> lcd.lcd_string("Raspberry PI", 2)
>>> lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
>>> lcd.lcd_string("Hello world", 2)

 

실행 - 최종

$ sudo python
Python 2.7.3 (default, Mar 18 2014, 05:13:23) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.chdir('/home/pi')
>>> import lcd
>>> lcd.lcd_init()
>>> lcd.lcd_byte(lcd.LCD_LINE_1, lcd.LCD_CMD)
>>> lcd.lcd_string("Raspberry PI", 2)
>>> lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
>>> lcd.lcd_string("Hello world", 2)
>>> lcd.GPIO.cleanup()
>>> quit()

소스 lcd.py

#!/usr/bin/python
#
# HD44780 LCD Test Script for
# Raspberry Pi
#
# Author : Matt Hawkins
# Site   : http://www.raspberrypi-spy.co.uk
# 
# Date   : 03/08/2012
#

# The wiring for the LCD is as follows:
# 1 : GND
# 2 : 5V
# 3 : Contrast (0-5V)*
# 4 : RS (Register Select)
# 5 : R/W (Read Write)       - GROUND THIS PIN
# 6 : Enable or Strobe
# 7 : Data Bit 0             - NOT USED
# 8 : Data Bit 1             - NOT USED
# 9 : Data Bit 2             - NOT USED
# 10: Data Bit 3             - NOT USED
# 11: Data Bit 4
# 12: Data Bit 5
# 13: Data Bit 6
# 14: Data Bit 7
# 15: LCD Backlight +5V**
# 16: LCD Backlight GND

#import
import RPi.GPIO as GPIO
import time

# Define GPIO to LCD mapping
LCD_RS = 7
LCD_E  = 8
LCD_D4 = 25
LCD_D5 = 24
LCD_D6 = 23
LCD_D7 = 18
#LED_ON = 15

# Define some device constants
LCD_WIDTH = 16    # Maximum characters per line
LCD_CHR = True
LCD_CMD = False

LCD_LINE_1 = 0x80 # LCD RAM address for the 1st line
LCD_LINE_2 = 0xC0 # LCD RAM address for the 2nd line 

# Timing constants
E_PULSE = 0.00005
E_DELAY = 0.00005

def main():
  # Main program block

  # Initialise display
  lcd_init()

  # Toggle backlight on-off-on
  #GPIO.output(LED_ON, True)
  #time.sleep(1)
  #GPIO.output(LED_ON, False)
  #time.sleep(1)
  #GPIO.output(LED_ON, True)
  #time.sleep(1)

  # Send some centred test
  lcd_byte(LCD_LINE_1, LCD_CMD)
  lcd_string("Rasbperry Pi",2)
  lcd_byte(LCD_LINE_2, LCD_CMD)
  lcd_string("Model B",2)

  time.sleep(3) # 3 second delay

  # Send some left justified text
  lcd_byte(LCD_LINE_1, LCD_CMD)
  lcd_string("1234567890123456",1)
  lcd_byte(LCD_LINE_2, LCD_CMD)
  lcd_string("abcdefghijklmnop",1)

  time.sleep(3) # 3 second delay

  # Send some right justified text
  lcd_byte(LCD_LINE_1, LCD_CMD)
  lcd_string("Raspberrypi-spy",3)
  lcd_byte(LCD_LINE_2, LCD_CMD)
  lcd_string(".co.uk",3)

  time.sleep(30)

  # Turn off backlight
  #GPIO.output(LED_ON, False)

def lcd_init():
  GPIO.setmode(GPIO.BCM)       # Use BCM GPIO numbers
  GPIO.setup(LCD_E, GPIO.OUT)  # E
  GPIO.setup(LCD_RS, GPIO.OUT) # RS
  GPIO.setup(LCD_D4, GPIO.OUT) # DB4
  GPIO.setup(LCD_D5, GPIO.OUT) # DB5
  GPIO.setup(LCD_D6, GPIO.OUT) # DB6
  GPIO.setup(LCD_D7, GPIO.OUT) # DB7
  #GPIO.setup(LED_ON, GPIO.OUT) # Backlight enable  
  # Initialise display
  lcd_byte(0x33,LCD_CMD)
  lcd_byte(0x32,LCD_CMD)
  lcd_byte(0x28,LCD_CMD)
  lcd_byte(0x0C,LCD_CMD)  
  lcd_byte(0x06,LCD_CMD)
  lcd_byte(0x01,LCD_CMD)  

def lcd_string(message,style):
  # Send string to display
  # style=1 Left justified
  # style=2 Centred
  # style=3 Right justified

  if style==1:
    message = message.ljust(LCD_WIDTH," ")  
  elif style==2:
    message = message.center(LCD_WIDTH," ")
  elif style==3:
    message = message.rjust(LCD_WIDTH," ")

  for i in range(LCD_WIDTH):
    lcd_byte(ord(message[i]),LCD_CHR)

def lcd_byte(bits, mode):
  # Send byte to data pins
  # bits = data
  # mode = True  for character
  #        False for command

  GPIO.output(LCD_RS, mode) # RS

  # High bits
  GPIO.output(LCD_D4, False)
  GPIO.output(LCD_D5, False)
  GPIO.output(LCD_D6, False)
  GPIO.output(LCD_D7, False)
  if bits&0x10==0x10:
    GPIO.output(LCD_D4, True)
  if bits&0x20==0x20:
    GPIO.output(LCD_D5, True)
  if bits&0x40==0x40:
    GPIO.output(LCD_D6, True)
  if bits&0x80==0x80:
    GPIO.output(LCD_D7, True)

  # Toggle 'Enable' pin
  time.sleep(E_DELAY)    
  GPIO.output(LCD_E, True)  
  time.sleep(E_PULSE)
  GPIO.output(LCD_E, False)  
  time.sleep(E_DELAY)      

  # Low bits
  GPIO.output(LCD_D4, False)
  GPIO.output(LCD_D5, False)
  GPIO.output(LCD_D6, False)
  GPIO.output(LCD_D7, False)
  if bits&0x01==0x01:
    GPIO.output(LCD_D4, True)
  if bits&0x02==0x02:
    GPIO.output(LCD_D5, True)
  if bits&0x04==0x04:
    GPIO.output(LCD_D6, True)
  if bits&0x08==0x08:
    GPIO.output(LCD_D7, True)

  # Toggle 'Enable' pin
  time.sleep(E_DELAY)    
  GPIO.output(LCD_E, True)  
  time.sleep(E_PULSE)
  GPIO.output(LCD_E, False)  
  time.sleep(E_DELAY)   

if __name__ == '__main__':
  main()

pi4j - 핀 배열

pi4j - 예제

import java.text.SimpleDateFormat;
import java.util.Date;

import com.pi4j.component.lcd.LCDTextAlignment;
import com.pi4j.component.lcd.impl.GpioLcdDisplay;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiGpioProvider;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.RaspiPinNumberingScheme;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;

public class LcdExample2 {

	public final static int LCD_ROWS = 2;
	public final static int LCD_ROW_1 = 0;
	public final static int LCD_ROW_2 = 1;
	public final static int LCD_COLUMNS = 16;
	public final static int LCD_BITS = 4;

	public static void main(String args[]) throws InterruptedException {

		System.out.println("<--Pi4J--> GPIO 4 bit LCD example program");
		
		// create gpio controller
		final GpioController gpio = GpioFactory.getInstance();

		// initialize LCD
		//new GpioLcdDisplay(LCD_ROWS, LCD_COLUMNS, RaspiPin.GPIO_06, RaspiPin.GPIO_05, RaspiPin.GPIO_04, RaspiPin.GPIO_00, RaspiPin.GPIO_01, RaspiPin.GPIO_03);
		final GpioLcdDisplay lcd = new GpioLcdDisplay(LCD_ROWS, // number of row
																														// supported by LCD
				LCD_COLUMNS, // number of columns supported by LCD
				RaspiPin.GPIO_11, // LCD RS pin          7
				RaspiPin.GPIO_10, // LCD strobe pin      8
				RaspiPin.GPIO_06, // LCD data bit 1     25
				RaspiPin.GPIO_05, // LCD data bit 2     24
				RaspiPin.GPIO_04, // LCD data bit 3     23
				RaspiPin.GPIO_01); // LCD data bit 4    18

		// provision gpio pins as input pins with its internal pull up resistor
		// enabled
		/*
		final GpioPinDigitalInput myButtons[] = { 
				gpio.provisionDigitalInputPin(RaspiPin.GPIO_13, "B1", PinPullResistance.PULL_UP),
				gpio.provisionDigitalInputPin(RaspiPin.GPIO_07, "B2", PinPullResistance.PULL_UP),
				gpio.provisionDigitalInputPin(RaspiPin.GPIO_04, "B3", PinPullResistance.PULL_UP),
				gpio.provisionDigitalInputPin(RaspiPin.GPIO_12, "B4", PinPullResistance.PULL_UP)
		};

		// create and register gpio pin listener
		gpio.addListener(new GpioPinListenerDigital() {
			@Override
			public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
				if (event.getState() == PinState.LOW) {
					lcd.writeln(LCD_ROW_2, event.getPin().getName() + " PRESSED", LCDTextAlignment.ALIGN_CENTER);
				} else {
					lcd.writeln(LCD_ROW_2, event.getPin().getName() + " RELEASED", LCDTextAlignment.ALIGN_CENTER);
				}
			}
		}, myButtons);
		*/
		
		// clear LCD
		lcd.clear();
		Thread.sleep(1000);

		// write line 1 to LCD
		lcd.write(LCD_ROW_1, "The Pi4J Project");

		// write line 2 to LCD
		lcd.write(LCD_ROW_2, "----------------");

		// line data replacement
		for (int index = 0; index < 5; index++) {
			lcd.write(LCD_ROW_2, "----------------");
			Thread.sleep(500);
			lcd.write(LCD_ROW_2, "****************");
			Thread.sleep(500);
		}
		lcd.write(LCD_ROW_2, "----------------");

		// single character data replacement
		for (int index = 0; index < lcd.getColumnCount(); index++) {
			lcd.write(LCD_ROW_2, index, ">");
			if (index > 0)
				lcd.write(LCD_ROW_2, index - 1, "-");
			Thread.sleep(300);
		}
		for (int index = lcd.getColumnCount() - 1; index >= 0; index--) {
			lcd.write(LCD_ROW_2, index, "<");
			if (index < lcd.getColumnCount() - 1)
				lcd.write(LCD_ROW_2, index + 1, "-");
			Thread.sleep(300);
		}

		// left alignment, full line data
		lcd.write(LCD_ROW_2, "----------------");
		Thread.sleep(500);
		lcd.writeln(LCD_ROW_2, "<< LEFT");
		Thread.sleep(1000);

		// right alignment, full line data
		lcd.write(LCD_ROW_2, "----------------");
		Thread.sleep(500);
		lcd.writeln(LCD_ROW_2, "RIGHT >>", LCDTextAlignment.ALIGN_RIGHT);
		Thread.sleep(1000);

		// center alignment, full line data
		lcd.write(LCD_ROW_2, "----------------");
		Thread.sleep(500);
		lcd.writeln(LCD_ROW_2, "<< CENTER >>", LCDTextAlignment.ALIGN_CENTER);
		Thread.sleep(1000);

		// mixed alignments, partial line data
		lcd.write(LCD_ROW_2, "----------------");
		Thread.sleep(500);
		lcd.write(LCD_ROW_2, "<L>", LCDTextAlignment.ALIGN_LEFT);
		lcd.write(LCD_ROW_2, "<R>", LCDTextAlignment.ALIGN_RIGHT);
		lcd.write(LCD_ROW_2, "CC", LCDTextAlignment.ALIGN_CENTER);
		Thread.sleep(3000);

		SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");

		// update time
		while (true) {
			// write time to line 2 on LCD
			//if (gpio.isHigh(myButtons)) {
				lcd.writeln(LCD_ROW_2, formatter.format(new Date()), LCDTextAlignment.ALIGN_CENTER);
			//}
			Thread.sleep(1000);
		}

		// 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(); <--- implement this method call if you wish to terminate
		// the Pi4J GPIO controller
	}
}

컴파일 및 실행

$ javac -cp ../lib/pi4j-core.jar:../lib/pi4j-device.jar LcdExample2.java
$ sudo java -cp .:../lib/pi4j-core.jar:../lib/pi4j-device.jar LcdExample2

실행 결과



728x90
728x90

출처 : Configure Tomcat service linux
Installing Tomcat as a Linux Service
라즈베리파이(Raspberry Pi) 아파치 톰캣 서버(Tomcat Server) 설치방법 (JSP 서블릿 컨테이너, 자바 웹서버 구축)
sharplet/tomcat-init

tomcat7 설치

$ cd /usr/local
$ sudo wget http://apache.tt.co.kr/tomcat/tomcat-7/v7.0.75/bin/apache-tomcat-7.0.75.tar.gz
$ sudo tar -xvf apache-tomcat-7.0.75.tar.gz

tomcat 서비스 등록 - tomcat 파일 생성하기 

tomcat

$ sudo vi /etc/init.d/tomcat

#!/bin/sh
#
# /etc/init.d/tomcat7 -- startup script for the Tomcat 7 servlet engine
#
# Written by Miquel van Smoorenburg .
# Modified for Debian GNU/Linux	by Ian Murdock .
# Modified for Tomcat by Stefan Gybas .
# Modified for Tomcat6 by Thierry Carrez .
# Modified for Tomcat7 by Ernesto Hernandez-Novich .
# Additional improvements by Jason Brittain .
#
### BEGIN INIT INFO
# Provides:          tomcat7
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# Should-Start:      $named
# Should-Stop:       $named
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start Tomcat.
# Description:       Start the Tomcat servlet engine.
# sudo update-rc.d tomcat defaults
# sudo update-rc.d tomcat remove
# ls /etc/rc0.d
### END INIT INFO

set -e

## Source function library.
#. /etc/rc.d/init.d/functions
export JAVA_HOME=/usr/lib/jvm/jdk-8-oracle-arm-vfp-hflt
export JAVA_OPTS="-Dfile.encoding=UTF-8 \
  -Dcatalina.logbase=/var/log/tomcat7 \
  -Dnet.sf.ehcache.skipUpdateCheck=true \
  -XX:+DoEscapeAnalysis \
  -XX:+UseConcMarkSweepGC \
  -XX:+CMSClassUnloadingEnabled \
  -XX:+UseParNewGC \
  -XX:MaxPermSize=128m \
  -Xms512m -Xmx512m"
export PATH=$JAVA_HOME/bin:$PATH
export TOMCAT_USER=root
export TOMCAT_HOME=/usr/local/apache-tomcat-7.0.75
export SHUTDOWN_WAIT=20

tomcat_pid() {
  echo `ps aux | grep org.apache.catalina.startup.Bootstrap | grep -v grep | awk '{ print $2 }'`
}

start() {
  pid=$(tomcat_pid)
  if [ -n "$pid" ] 
  then
    echo "Tomcat is already running (pid: $pid)"
  else
    # Start tomcat
    echo "Starting tomcat"
    ulimit -n 100000
    umask 007
    /bin/su - $TOMCAT_USER -c $TOMCAT_HOME/bin/startup.sh
  fi


  return 0
}

stop() {
  pid=$(tomcat_pid)
  if [ -n "$pid" ]
  then
    echo "Stoping Tomcat"
    /bin/su - $TOMCAT_USER -c $TOMCAT_HOME/bin/shutdown.sh

    let kwait=$SHUTDOWN_WAIT
    count=0;
    until [ `ps -p $pid | grep -c $pid` = '0' ] || [ $count -gt $kwait ]
    do
      echo -n -e "\nwaiting for processes to exit";
      sleep 1
      let count=$count+1;
    done

    if [ $count -gt $kwait ]; then
      echo -n -e "\nkilling processes which didn't stop after $SHUTDOWN_WAIT seconds\n"
      kill -9 $pid
    fi
  else
    echo "Tomcat is not running"
  fi
 
  return 0
}

case $1 in
start)
  start
;; 
stop)   
  stop
;; 
restart)
  stop
  start
;;
status)
  pid=$(tomcat_pid)
  if [ -n "$pid" ]
  then
    echo "Tomcat is running with pid: $pid"
  else
    echo "Tomcat is not running"
  fi
;; 
esac    
exit 0

tomcat 권한설정

$ sudo chmod u+x /etc/init.d/tomcat

tomcat 실행 스크립트 파일 부팅시 자동으로 되도록 복사

$ sudo update-rc.d tomcat defaults

tomcat 서비스 명령으로 실행

$ sudo service tomcat restart
728x90
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;
  }
}

728x90

+ Recent posts