Raspberry PI(slave) - Arduino(master) SPI 통신

OS/Raspberry Pi 2016.09.04 02:00 Posted by 파란크리스마스

출처 : Raspberry Pi to Arduino SPI Communication

spi 확인

$ gpio load spi
gpio: Unable to load/unload modules as this Pi has the device tree enabled.
  You need to run the raspi-config program (as root) and select the
  modules (SPI or I2C) that you wish to load/unload there and reboot.
  There is more information here:
      https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=97314

배선

소스 - Arduino (Master)

/*************************************************************
 SPI_Hello_Raspi
   Configures an ATMEGA as an SPI slave and demonstrates
   bidirectional communication with an Raspberry Pi SPI master
   by repeatedly sending the text "Hello Raspi"
****************************************************************/


/***************************************************************
 Global Variables
  -hello[] is an array to hold the data to be transmitted
  -marker is used as a pointer in traversing data arrays
/***************************************************************/

unsigned char hello[] = {'H','e','l','l','o',' ',
                         'R','a','s','p','i','\n'};
byte marker = 0;
 

/***************************************************************  
 Setup SPI in slave mode (1) define MISO pin as output (2) set
 enable bit of the SPI configuration register 
****************************************************************/ 
                    
void setup (void)
{
 
  pinMode(MISO, OUTPUT);
  SPCR |= _BV(SPE);

  Serial.begin(115200);
}  

/***************************************************************  
 Loop until the SPI End of Transmission Flag (SPIF) is set
 indicating a byte has been received.  When a byte is
 received, load the next byte in the Hello[] array into SPDR
 to be transmitted to the Raspberry Pi, and increment the marker.
 If the end of the Hell0[] array has been reached, reset
 marker to 0.
****************************************************************/

void loop (void)
{

  if((SPSR & (1 << SPIF)) != 0)
  {
    SPDR = hello[marker];
    marker++;
   
    if(marker > sizeof(hello))
    {
      marker = 0;
    }  
  }

  Serial.println('test');
}

소스 - Raspberry PI (Slave)

/**********************************************************
 SPI_Raspi_Arduino
   Configures an Raspberry Pi as an SPI master and
   demonstrates a basic bidirectional communication scheme
   with an Arduino slave.  The Raspberry Pi transmits
   commands to perform addition and subtraction on a pair
   of integers and the Ardunio returns the result

Compile String:
g++ -o SPI_Raspi_Arduino SPI_Raspi_Arduino.cpp
***********************************************************/

#include <sys/ioctl.h>
#include <linux/spi/spidev.h>
#include <fcntl.h>
#include <iostream>
#include <cstring>
#include <unistd.h>

using namespace std;


/**********************************************************
Housekeeping variables
***********************************************************/
int results;
int fd;

/**********************************************************
Declare Functions
***********************************************************/

int spiTxRx(unsigned char txDat);
int sendCommand(char i, int j, int k);

/**********************************************************
Main
***********************************************************/

int main (void)
{

/**********************************************************
Setup SPI
Open file spidev0.0 (chip enable 0) for read/write access
with the file descriptor "fd"
Configure transfer speed (1MkHz)
***********************************************************/

   fd = open("/dev/spidev0.0", O_RDWR);

   unsigned int speed = 1000000;
   ioctl (fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);

/**********************************************************
An endless loop that repeatedly sends the demonstration
commands to the Arduino and displays the results
***********************************************************/

   while (1)
   {

      results = sendCommand('a', 510, 655);

      cout << "Addition results:" << endl;
      cout << "510 + 655 = " <<  (int)(results) << endl;


      results = sendCommand('s', 1000, 250);

      cout << "Subtraction results:" << endl;
      cout << "1000 - 250 = " <<  (int)(results) << endl <<endl; 

      sleep(1);

     }

}

/**********************************************************
spiTxRx
 Transmits one byte via the SPI device, and returns one byte
 as the result.

 Establishes a data structure, spi_ioc_transfer as defined
 by spidev.h and loads the various members to pass the data
 and configuration parameters to the SPI device via IOCTL

 Local variables txDat and rxDat are defined and passed by
 reference.  
***********************************************************/

int spiTxRx(unsigned char txDat)
{
 
  unsigned char rxDat;

  struct spi_ioc_transfer spi;

  memset (&spi, 0, sizeof (spi));

  spi.tx_buf        = (unsigned long)&txDat;
  spi.rx_buf        = (unsigned long)&rxDat;
  spi.len           = 1;

  ioctl (fd, SPI_IOC_MESSAGE(1), &spi);

  return rxDat;
}


/**********************************************************
sendCommand
 Demonstration of a protocol that uses the spiTxRx function
 to send a formatted command sequence/packet to the Arduino
 one byte at and capture the results
***********************************************************/


int sendCommand(char command, int j, int k)
{

unsigned char resultByte;
bool ack;

/**********************************************************
Unions allow variables to occupy the same memory space
a convenient way to move back and forth between 8-bit and
16-bit values etc.

Here three unions are declared: two for parameters to be 
passed in commands to the Arduino and one to receive
the results
***********************************************************/

union p1Buffer_T       
{
  int p1Int;
  unsigned char  p1Char [2];
} p1Buffer;

union p2Buffer_T      
{
  int p2Int;
  unsigned char  p2Char [2];
} p2Buffer;

union resultBuffer_T     
{
  int resultInt;
  unsigned char  resultChar [2];
} resultBuffer;


  p1Buffer.p1Int = j;
  p2Buffer.p2Int = k;
  resultBuffer.resultInt = 0;

/**********************************************************
An initial handshake sequence sends a one byte start code
('c') and loops endlessly until it receives the one byte 
acknowledgment code ('a') and sets the ack flag to true.
(Note that the loop also sends the command byte while 
still in handshake sequence to avoid wasting a transmit
cycle.)
***********************************************************/

  do
  {
    ack = false;

    spiTxRx('c');
    usleep (10);


    resultByte = spiTxRx(command);
    if (resultByte == 'a')
    {
      ack = true;
    }
    usleep (10);  

   }
  while (ack == false);

/**********************************************************
Send the parameters one byte at a time.
***********************************************************/

  spiTxRx(p1Buffer.p1Char[0]);
  usleep (10);


  spiTxRx(p1Buffer.p1Char[1]);
  usleep (10);


  spiTxRx(p2Buffer.p2Char[0]);
  usleep (10);


  spiTxRx(p2Buffer.p2Char[1]);
  usleep (10);

/**********************************************************
Push two more zeros through so the Arduino can return the
results
***********************************************************/


  resultByte = spiTxRx(0);
  resultBuffer.resultChar[0] = resultByte;
  usleep (10);


  resultByte = spiTxRx(0);
  resultBuffer.resultChar[1] = resultByte;
  return resultBuffer.resultInt;

}

컴파일

$ g++ -o SPI_Raspi_Arduino SPI_Raspi_Arduino.cpp

실행

$ sudo ./SPI_Raspi_Arduino
Addition results:
510 + 655 = 108
Subtraction results:
1000 - 250 = 28672
 
Addition results:
510 + 655 = 2
Subtraction results:
1000 - 250 = 0
 
Addition results:
510 + 655 = 28674
Subtraction results:
1000 - 250 = 28672
 
Addition results:
510 + 655 = 28674
Subtraction results:
1000 - 250 = 28672
 
Addition results:
510 + 655 = 2
Subtraction results:
1000 - 250 = 0
 
^C
저작자 표시
신고

Raspberry PI(master) - Arduino(slave) SPI 통신

OS/Raspberry Pi 2016.09.04 01:17 Posted by 파란크리스마스

출처 : Raspberry Pi + Arduino + SPI - MitchTech | MitchTech

배선

소스 - Arduino (Slave)

// Written by Nick Gammon
// February 2011
/**
 * Send arbitrary number of bits at whatever clock rate (tested at 500 KHZ and 500 HZ).
 * This script will capture the SPI bytes, when a '\n' is recieved it will then output
 * the captured byte stream via the serial.
 */

#include <SPI.h>

char buf [100];
volatile byte pos;
volatile boolean process_it;

void setup (void)
{
  Serial.begin (115200);   // debugging

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);
  
  // turn on SPI in slave mode
  SPCR |= _BV(SPE);
  
  // get ready for an interrupt 
  pos = 0;   // buffer empty
  process_it = false;

  // now turn on interrupts
  SPI.attachInterrupt();

}  // end of setup


// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register
  
  // add to buffer if room
  if (pos < sizeof buf)
    {
    buf [pos++] = c;
    
    // example: newline means time to process buffer
    if (c == '\n')
      process_it = true;
      
    }  // end of room available
}  // end of interrupt routine SPI_STC_vect

// main loop - wait for flag set in interrupt routine
void loop (void)
{
  if (process_it)
    {
    buf [pos] = 0;  
    Serial.println (buf);
    pos = 0;
    process_it = false;
    }  // end of flag set
    
}  // end of loop

소스 - Raspberry PI (Master)

/*
 * SPI testing utility (using spidev driver)
 *
 * Copyright (c) 2007  MontaVista Software, Inc.
 * Copyright (c) 2007  Anton Vorontsov <avorontsov@ru.mvista.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License.
 *
 * Cross-compile with cross-gcc -I/path/to/cross-kernel/include
 */

#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/types.h>
#include <linux/spi/spidev.h>

#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))

static void pabort(const char *s)
{
	perror(s);
	abort();
}

static const char *device = "/dev/spidev0.0";
static uint8_t mode;
static uint8_t bits = 8;
static uint32_t speed = 500000;
static uint16_t delay;

static void transfer(int fd)
{
	int ret;
	uint8_t tx[] = {
        0x48, 0x45, 0x4C, 0x4C, 0x4F,
        0x20, 
        0x57, 0x4F, 0x52, 0x4C, 0x44,
        0x0A 
	};
	uint8_t rx[ARRAY_SIZE(tx)] = {0, };
	struct spi_ioc_transfer tr = {
		.tx_buf = (unsigned long)tx,
		.rx_buf = (unsigned long)rx,
		.len = ARRAY_SIZE(tx),
		.delay_usecs = delay,
		.speed_hz = speed,
		.bits_per_word = bits,
	};

	ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
	if (ret < 1)
		pabort("can't send spi message");

    /*
	for (ret = 0; ret < ARRAY_SIZE(tx); ret++) {
		if (!(ret % 6))
			puts("");
		printf("%.2X ", rx[ret]);
	}
	puts("");
    */
}

static void print_usage(const char *prog)
{
	printf("Usage: %s [-DsbdlHOLC3]\n", prog);
	puts("  -D --device   device to use (default /dev/spidev1.1)\n"
	     "  -s --speed    max speed (Hz)\n"
	     "  -d --delay    delay (usec)\n"
	     "  -b --bpw      bits per word \n"
	     "  -l --loop     loopback\n"
	     "  -H --cpha     clock phase\n"
	     "  -O --cpol     clock polarity\n"
	     "  -L --lsb      least significant bit first\n"
	     "  -C --cs-high  chip select active high\n"
	     "  -3 --3wire    SI/SO signals shared\n");
	exit(1);
}

static void parse_opts(int argc, char *argv[])
{
	while (1) {
		static const struct option lopts[] = {
			{ "device",  1, 0, 'D' },
			{ "speed",   1, 0, 's' },
			{ "delay",   1, 0, 'd' },
			{ "bpw",     1, 0, 'b' },
			{ "loop",    0, 0, 'l' },
			{ "cpha",    0, 0, 'H' },
			{ "cpol",    0, 0, 'O' },
			{ "lsb",     0, 0, 'L' },
			{ "cs-high", 0, 0, 'C' },
			{ "3wire",   0, 0, '3' },
			{ "no-cs",   0, 0, 'N' },
			{ "ready",   0, 0, 'R' },
			{ NULL, 0, 0, 0 },
		};
		int c;

		c = getopt_long(argc, argv, "D:s:d:b:lHOLC3NR", lopts, NULL);

		if (c == -1)
			break;

		switch (c) {
		case 'D':
			device = optarg;
			break;
		case 's':
			speed = atoi(optarg);
			break;
		case 'd':
			delay = atoi(optarg);
			break;
		case 'b':
			bits = atoi(optarg);
			break;
		case 'l':
			mode |= SPI_LOOP;
			break;
		case 'H':
			mode |= SPI_CPHA;
			break;
		case 'O':
			mode |= SPI_CPOL;
			break;
		case 'L':
			mode |= SPI_LSB_FIRST;
			break;
		case 'C':
			mode |= SPI_CS_HIGH;
			break;
		case '3':
			mode |= SPI_3WIRE;
			break;
		case 'N':
			mode |= SPI_NO_CS;
			break;
		case 'R':
			mode |= SPI_READY;
			break;
		default:
			print_usage(argv[0]);
			break;
		}
	}
}

int main(int argc, char *argv[])
{
	int ret = 0;
	int fd;

	parse_opts(argc, argv);

	fd = open(device, O_RDWR);
	if (fd < 0)
		pabort("can't open device");

	/*
	 * spi mode
	 */
	ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
	if (ret == -1)
		pabort("can't set spi mode");

	ret = ioctl(fd, SPI_IOC_RD_MODE, &mode);
	if (ret == -1)
		pabort("can't get spi mode");

	/*
	 * bits per word
	 */
	ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
	if (ret == -1)
		pabort("can't set bits per word");

	ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits);
	if (ret == -1)
		pabort("can't get bits per word");

	/*
	 * max speed hz
	 */
	ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
	if (ret == -1)
		pabort("can't set max speed hz");

	ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed);
	if (ret == -1)
		pabort("can't get max speed hz");

	printf("spi mode: %d\n", mode);
	printf("bits per word: %d\n", bits);
	printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000);

	transfer(fd);

	close(fd);

	return ret;
}

컴파일

$ gcc spidev_test.c -o spidev_test

실행

$ sudo ./spidev_test
spi mode: 0
bits per word: 8
max speed: 500000 Hz (500 KHz)

결과

저작자 표시
신고

Raspberry PI - i2c 통신 - PCA9685

OS/Raspberry Pi 2016.08.02 02:05 Posted by 파란크리스마스

출처 : Raspberry Pi SPI and I2C Tutorial
Use the Adafruit PCA9685 with a Raspberry PI, in Java Raspberry PI to drive up to 16 servos
JavaScript Robotics: Servo - PCA9685

I2C on Pi

$ sudo raspi-config

i2c device 활성화

$ sudo vi /etc/modules

# /etc/modules: kernel modules to load at boot time.
#
# This file contains the names of kernel modules that should be loaded
# at boot time, one per line. Lines beginning with "#" are ignored.

i2c-bcm2708
i2c-dev

gpio commands

$ gpio -v
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: Model B, Revision: 03, Memory: 512MB, Maker: Egoman 
  * Device tree is enabled.
  * This Raspberry Pi supports user-level GPIO access.
    -> See the man-page for more details
    -> ie. export WIRINGPI_GPIOMEM=1
$ gpio readall
 +-----+-----+---------+------+---+-Model B2-+---+------+---------+-----+-----+
 | BCM | wPi |   Name  | Mode | V | Physical | V | Mode | Name    | wPi | BCM |
 +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+
 |     |     |    3.3v |      |   |  1 || 2  |   |      | 5v      |     |     |
 |   2 |   8 |   SDA.1 | ALT0 | 1 |  3 || 4  |   |      | 5V      |     |     |
 |   3 |   9 |   SCL.1 | ALT0 | 1 |  5 || 6  |   |      | 0v      |     |     |
 |   4 |   7 | GPIO. 7 |   IN | 1 |  7 || 8  | 1 | ALT0 | TxD     | 15  | 14  |
 |     |     |      0v |      |   |  9 || 10 | 1 | ALT0 | RxD     | 16  | 15  |
 |  17 |   0 | GPIO. 0 |   IN | 0 | 11 || 12 | 0 | IN   | GPIO. 1 | 1   | 18  |
 |  27 |   2 | GPIO. 2 |   IN | 0 | 13 || 14 |   |      | 0v      |     |     |
 |  22 |   3 | GPIO. 3 |   IN | 0 | 15 || 16 | 0 | IN   | GPIO. 4 | 4   | 23  |
 |     |     |    3.3v |      |   | 17 || 18 | 0 | IN   | GPIO. 5 | 5   | 24  |
 |  10 |  12 |    MOSI | ALT0 | 0 | 19 || 20 |   |      | 0v      |     |     |
 |   9 |  13 |    MISO | ALT0 | 0 | 21 || 22 | 0 | IN   | GPIO. 6 | 6   | 25  |
 |  11 |  14 |    SCLK | ALT0 | 0 | 23 || 24 | 1 | OUT  | CE0     | 10  | 8   |
 |     |     |      0v |      |   | 25 || 26 | 1 | OUT  | CE1     | 11  | 7   |
 +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+
 |  28 |  17 | GPIO.17 |   IN | 0 | 51 || 52 | 0 | IN   | GPIO.18 | 18  | 29  |
 |  30 |  19 | GPIO.19 |   IN | 0 | 53 || 54 | 0 | IN   | GPIO.20 | 20  | 31  |
 +-----+-----+---------+------+---+----++----+---+------+---------+-----+-----+
 | BCM | wPi |   Name  | Mode | V | Physical | V | Mode | Name    | wPi | BCM |
 +-----+-----+---------+------+---+-Model B2-+---+------+---------+-----+-----+

detect I2C chips

출처 : i2cdetect(8): detect I2C chips - Linux man page

$ ls /dev/*i2c*
/dev/i2c-1
$ sudo apt-get install -y i2c-tools
$ i2cdetect -y 1
     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- -- 
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
40: 40 -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
70: 70 -- -- -- -- -- -- -- 

배선

PCA9685Gpio.java

출처 : wyliodrin-server-nodejs/libs/raspberrypi/java/pi4j/examples/PCA9685GpioExample.java

package com.bluexmas.arm;

import java.io.IOException;

/**
 * sudo java -cp .:pi4j-core.jar:pi4j-device.jar:pi4j-gpio-extension.jar:pi4j-service.jar com.bluexmas.arm.PCA9685Gpio
 */
import java.math.BigDecimal;

import com.pi4j.gpio.extension.pca.PCA9685GpioProvider;
import com.pi4j.gpio.extension.pca.PCA9685Pin;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinPwmOutput;
import com.pi4j.io.gpio.Pin;
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CFactory;
import com.pi4j.io.i2c.I2CFactory.UnsupportedBusNumberException;

public class PCA9685Gpio {
	
	private static final int SERVO_DURATION_MIN = 650;
	private static final int SERVO_DURATION_NEUTRAL = 1500;
	private static final int SERVO_DURATION_MAX = 2100;
	
	private static PCA9685Gpio instance = null;
	
	private PCA9685GpioProvider gpioProvider = null;
	
	private PCA9685Gpio() throws IOException, UnsupportedBusNumberException {		
		System.out.println("<--Pi4J--> PCA9685 PWM Example ... started.");
		// This would theoretically lead into a resolution of 5 microseconds per
		// step:
		// 4096 Steps (12 Bit)
		// T = 4096 * 0.000005s = 0.02048s
		// f = 1 / T = 48.828125
		BigDecimal frequency = new BigDecimal("48.828");
		// Correction factor: actualFreq / targetFreq
		// e.g. measured actual frequency is: 51.69 Hz
		// Calculate correction factor: 51.65 / 48.828 = 1.0578
		// --> To measure actual frequency set frequency without correction
		// factor(or set to 1)
		BigDecimal frequencyCorrectionFactor = new BigDecimal("1.0578");
		// Create custom PCA9685 GPIO provider
		I2CBus bus = I2CFactory.getInstance(I2CBus.BUS_1);
		gpioProvider = new PCA9685GpioProvider(bus, 0x40, frequency, frequencyCorrectionFactor);
		// Define outputs in use for this example
		GpioPinPwmOutput[] myOutputs = provisionPwmOutputs(gpioProvider);
		// Reset outputs
		gpioProvider.reset();
	}
	
	public static PCA9685Gpio getInstance() throws IOException, UnsupportedBusNumberException {
		if (instance==null) instance = new PCA9685Gpio();
		return instance;
	}
	
	public void setPwm(Pin pin, int duration) {
		gpioProvider.setPwm(pin, duration);
	}
	
	public void shutdown() {
		gpioProvider.shutdown();
	}
	
	private static GpioPinPwmOutput[] provisionPwmOutputs(final PCA9685GpioProvider gpioProvider) {
		GpioController gpio = GpioFactory.getInstance();
		GpioPinPwmOutput myOutputs[] = { 
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_00, "Pulse 00"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_01, "Pulse 01"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_02, "Pulse 02"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_03, "Pulse 03"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_04, "Pulse 04"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_05, "Pulse 05"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_06, "Pulse 06"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_07, "Pulse 07"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_08, "Pulse 08"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_09, "Pulse 09"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_10, "Always ON"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_11, "Always OFF"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_12, "Servo pulse MIN"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_13, "Servo pulse NEUTRAL"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_14, "Servo pulse MAX"),
				gpio.provisionPwmOutputPin(gpioProvider, PCA9685Pin.PWM_15, "not used") };
		return myOutputs;
	}

	public static void main(String[] args) throws Exception {
		
		PCA9685Gpio test = PCA9685Gpio.getInstance();
		
		test.setPwm(PCA9685Pin.PWM_00, SERVO_DURATION_MIN);
		// Set 1.5ms pulse (R/C Servo neutral position)
		Thread.sleep(2000);
		test.setPwm(PCA9685Pin.PWM_00, SERVO_DURATION_NEUTRAL);
		// Set 2.1ms pulse (R/C Servo maximum position)
		Thread.sleep(2000);
		test.setPwm(PCA9685Pin.PWM_00, SERVO_DURATION_MAX);
		Thread.sleep(2000);
		test.setPwm(PCA9685Pin.PWM_00, SERVO_DURATION_MIN);
		Thread.sleep(2000);
		test.shutdown();
	}
	
}

실행

$ sudo java -cp .:pi4j-core.jar:pi4j-gpio-extension.jar com.bluexmas.arm.PCA9685Gpio
<--Pi4J--> PCA9685 PWM Example ... started.

저작자 표시
신고

RaspberryPi - KY-015_DHT11(온도, 습도 센서)

OS/Raspberry Pi 2016.07.10 03:57 Posted by 파란크리스마스

출처 : java - read temperature from DHT11, using pi4j - Stack Overflow

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 

핀 연결

   

DHT11.java

import java.util.List;
import java.util.ArrayList;

import com.pi4j.wiringpi.Gpio;
import com.pi4j.wiringpi.GpioUtil;

public class DHT11 {
	private static final int MAXTIMINGS = 85;
	private int[] dht11_dat = { 0, 0, 0, 0, 0 };

	public DHT11() {

	    // setup wiringPi
	    if (Gpio.wiringPiSetup() == -1) {
	        System.out.println(" ==>> GPIO SETUP FAILED");
	        return;
	    }

	   GpioUtil.export(3, GpioUtil.DIRECTION_OUT);            
	}

	public void getTemperature() {
	   int laststate = Gpio.HIGH;
	   int j = 0;
	   dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
	   StringBuilder value = new StringBuilder();

	   Gpio.pinMode(3, Gpio.OUTPUT);
	   Gpio.digitalWrite(3, Gpio.LOW);
	   Gpio.delay(18);

	   Gpio.digitalWrite(3, Gpio.HIGH);        
	   Gpio.pinMode(3, Gpio.INPUT);

	   for (int i = 0; i < MAXTIMINGS; i++) {
	      int counter = 0;
	      while (Gpio.digitalRead(3) == laststate) {
	          counter++;
	          Gpio.delayMicroseconds(1);
	          if (counter == 255) {
	              break;
	          }
	      }

	      laststate = Gpio.digitalRead(3);

	      if (counter == 255) {
	          break;
	      }

	      /* ignore first 3 transitions */
	      if ((i >= 4) && (i % 2 == 0)) {
	         /* shove each bit into the storage bytes */
	         dht11_dat[j / 8] <<= 1;
	         if (counter > 16) {
	             dht11_dat[j / 8] |= 1;
	         }
	         j++;
	       }
	    }
	    // check we read 40 bits (8bit x 5 ) + verify checksum in the last
	    // byte
	    if ((j >= 40) && checkParity()) {
	        float h = (float)((dht11_dat[0] << 8) + dht11_dat[1]) / 10;
	        if ( h > 100 )
	        {
	            h = dht11_dat[0];   // for DHT11
	        }
	        float c = (float)(((dht11_dat[2] & 0x7F) << 8) + dht11_dat[3]) / 10;
	        if ( c > 125 )
	        {
	            c = dht11_dat[2];   // for DHT11
	        }
	        if ( (dht11_dat[2] & 0x80) != 0 )
	        {
	            c = -c;
	        }
	        float f = c * 1.8f + 32;
	        System.out.println( "Humidity = " + h + " Temperature = " + c + "(" + f + "f)");
	    }else  {
	        System.out.println( "Data not good, skip" );
	    }

	}

	private boolean checkParity() {
	  return (dht11_dat[4] == ((dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF));
	}



	public static void main (String ars[]) throws Exception {

	    DHT11 dht = new DHT11();

	    for (int i=0; i<10; i++) {
	       Thread.sleep(2000);
	       dht.getTemperature();
	    }

	    System.out.println("Done!!");

	}
}

컴파일

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

실행

$ sudo java -cp .:pi4j-1.0/lib/pi4j-core.jar DHT11 
Humidity = 56.0 Temperature = 32.0(89.6f)
Data not good, skip
Humidity = 53.0 Temperature = 31.0(87.8f)
Data not good, skip
Humidity = 52.0 Temperature = 31.0(87.8f)
Humidity = 52.0 Temperature = 31.0(87.8f)
Data not good, skip
Humidity = 51.0 Temperature = 31.0(87.8f)
Humidity = 51.0 Temperature = 31.0(87.8f)
Data not good, skip
Done!!

GPIO 핀 배열

저작자 표시
신고

RaspberryPi - HC-SR501(PIR 동작 검지 센서)

OS/Raspberry Pi 2016.07.10 01:58 Posted by 파란크리스마스

출처 : 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 핀 배열

저작자 표시
신고

Raspberry PI - 기초 파일

OS/Raspberry Pi 2016.05.27 23:08 Posted by 파란크리스마스

/etc/rc.local 파일   invalid-file

#!/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 파일   invalid-file

# 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 파일   invalid-file

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
저작자 표시
신고

Wiring Pi

OS/Raspberry Pi 2016.03.12 23:33 Posted by 파란크리스마스

출처 : 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

실행 결과

저작자 표시
신고

RaspberryPi - Serial 통신

OS/Raspberry Pi 2015.10.07 13:55 Posted by 파란크리스마스

출처 : 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...


저작자 표시
신고

RaspberryPI - 3D Camera streaming

OS/Raspberry Pi 2015.10.04 00:59 Posted by 파란크리스마스

출처 : 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의 프라스틱 버전에 핸드폰 설치 

저작자 표시
신고

RaspberryPI - HD44780 (1602a 16x2 Text Lcd) 제어하기

OS/Raspberry Pi 2015.10.02 00:36 Posted by 파란크리스마스

출처 : 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

실행 결과



저작자 표시
신고

RaspberryPI - Tomcat 설치

OS/Raspberry Pi 2015.08.23 20:41 Posted by 파란크리스마스

출처 : 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
저작자 표시
신고

RaspberryPI - GPIO로 LED 켜고 끄기

OS/Raspberry Pi 2015.08.13 23:55 Posted by 파란크리스마스

출처 : 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;
  }
}


저작자 표시
신고


 

티스토리 툴바