728x90

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

컴파일

X
user@localhost:~

[user@localhost]$ gcc spidev_test.c -o spidev_test

실행

X
user@localhost:~

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

결과

728x90
728x90

출처 : Analog Read Serial

배선

소스

/*
  AnalogReadSerial
  Reads an analog input on pin 0, prints the result to the serial monitor.
  Graphical representation is available using serial plotter (Tools > Serial Plotter menu)
  Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.

  This example code is in the public domain.
*/

// the setup routine runs once when you press reset:
void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 1:
  int sensorValue = analogRead(A1);
  // print out the value you read:
  Serial.println(sensorValue);
  delay(1);        // delay in between reads for stability
}

결과

728x90
728x90

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

X
user@localhost:~

[user@localhost]$ sudo raspi-config

i2c device 활성화

X
user@localhost:~

[user@localhost]$ 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

X
user@localhost:~

[user@localhost]$ 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
[user@localhost]$ 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

X
user@localhost:~

[user@localhost]$ ls /dev/*i2c*
/dev/i2c-1
[user@localhost]$ sudo apt-get install -y i2c-tools
[user@localhost]$ 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();
	}
	
}

실행

X
user@localhost:~

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

728x90
728x90

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

pi4j 다운로드

X
user@localhost:~

[user@localhost]$ mkdir pi4j
[user@localhost]$ cd pi4j
[user@localhost]$ 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]
 
[user@localhost]$ 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!!");

	}
}

컴파일

X
user@localhost:~

[user@localhost]$ javac -cp pi4j-1.0/lib/pi4j-core.jar DHT11.java

실행

X
user@localhost:~

[user@localhost]$ 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 핀 배열

728x90
728x90

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

pi4j 다운로드

X
user@localhost:~

[user@localhost]$ mkdir pi4j
[user@localhost]$ cd pi4j
[user@localhost]$ 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]
 
[user@localhost]$ 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);
        }

    }
}

컴파일

X
user@localhost:~

[user@localhost]$ javac -cp pi4j-1.0/lib/pi4j-core.jar MotionSensor.java

실행

X
user@localhost:~

[user@localhost]$ 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

펌웨어 업그레이드

X
user@localhost:~

[user@localhost]$ sudo BRANCH=next rpi-update
[user@localhost]$ sudo shutdown -r now

WIFI 자동연결 설정

출처 : Setting up WiFi connection

X
user@localhost:~

[user@localhost]$ sudo vi /etc/network/interfaces

내용 추가

auto wlan0

WIFI 절약모드 끄기

X
user@localhost:~

[user@localhost]$ sudo iwconfig wlan0 power off

서비스 비활성화

X
user@localhost:~

[user@localhost]$ sudo update-rc.d nginx disable
[user@localhost]$ sudo update-rc.d supervisor disable

728x90
728x90

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

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

X
user@localhost:~

[user@localhost]$ sudo apt-get update
[user@localhost]$ sudo apt-get upgrade

소스관리툴 git 다운로드

X
user@localhost:~

[user@localhost]$ sudo apt-get install git-core

wiringPi 소스 다운로드

X
user@localhost:~

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

wiringPi 컴파일

X
user@localhost:~

[user@localhost]$ ./build

wiringPi 설치확인

X
user@localhost:~

[user@localhost]$ 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 제어하기

소스 작성

X
user@localhost:~

[user@localhost]$ 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 ;
}

컴파일

X
user@localhost:~

[user@localhost]$ gcc -o led led.c -lwiringPi

실행

X
user@localhost:~

[user@localhost]$ 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 장착 확인

X
user@localhost:~

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

서비스 설치

X
user@localhost:~

[user@localhost]$ sudo apt-get install --no-install-recommends bluetooth

서비스 실행 확인

X
user@localhost:~

[user@localhost]$ 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)

X
user@localhost:~

[user@localhost]$ cat /boot/cmdline.txt
dwc_otg.lpm_enable=0 console=ttyAMA0,115200 console=tty1 root=/dev/mmcblk0p6 rootfstype=ext4 elevator=deadline rootwait
[user@localhost]$ 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)

X
user@localhost:~

[user@localhost]$ cd /boot
[user@localhost]$ sudo cp cmdline.txt cmdline.bak
[user@localhost]$ 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)

X
user@localhost:~

[user@localhost]$ 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 컴파일 관련 패키지 설치

X
user@localhost:~

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

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

X
user@localhost:~

[user@localhost]$ sudo apt-get install libbluetooth-dev

ant 설치

X
user@localhost:~

[user@localhost]$ sudo apt-get install ant

BlueCove ant 빌드

X
user@localhost:~

[user@localhost]$ 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 컴파일 및 실행

X
user@localhost:~

[user@localhost]$ wget http://get.pi4j.com/download/pi4j-1.1-SNAPSHOT.zip
[user@localhost]$ unzip pi4j-1.1-SNAPSHOT.zip
[user@localhost]$ cp /home/pi/bluecove-gpl-2.1.0/target/bluecove-gpl-2.1.0.jar ~/pi4j-1.1-SNAPSHOT/lib
[user@localhost]$ javac -cp lib/pi4j-core.jar:lib/bluecove-gpl-2.1.0.jar:lib/bluecove-2.1.0.jar SimpleSPPServer.java
[user@localhost]$ 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

+ Recent posts