Chart.js - Spring 연동

Programming/Java 2017.03.29 20:05 Posted by 파란크리스마스

Chart.js - Spring 연동

출처 : Chart.js - Spring 연동

JSONChartJS 클래스

package com.intel4.json;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.intel4.service.QuestionListService;
import com.intel4.util.BeanUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JSONChartJS extends JSONData {

	@Override
	public JSONObject getJSON(HttpServletRequest request, HttpServletResponse response) {

		String subcmd = request.getParameter("subcmd");
		JSONObject jobj_data = null;
		if (subcmd.equals("line")) {
			jobj_data = getAddData(request, response);
		}
		return jobj_data;
	}

	private JSONObject getAddData(HttpServletRequest request, HttpServletResponse response) {
		
		JSONArray datas = new JSONArray();
		
		JSONObject data1 = new JSONObject();
		data1.put("month", "1월");
		data1.put("pc", 100);
		data1.put("monitor", 80);
		datas.add(data1);
		JSONObject data2 = new JSONObject();
		data2.put("month", "2월");
		data2.put("pc", 80);
		data2.put("monitor", 70);
		datas.add(data2);
		JSONObject data3 = new JSONObject();
		data3.put("month", "3월");
		data3.put("pc", 70);
		data3.put("monitor", 60);
		datas.add(data3);
		JSONObject data4 = new JSONObject();
		data4.put("month", "4월");
		data4.put("pc", 90);
		data4.put("monitor", 100);
		datas.add(data4);
		JSONObject data5 = new JSONObject();
		data5.put("month", "5월");
		data5.put("pc", 40);
		data5.put("monitor", 110);
		datas.add(data5);
		
		JSONObject result = new JSONObject();
		result.put("datas", datas);
		
		return result;
	}
}

Line Chart

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!doctype html>
<html>

<head>
<title>Line Chart</title>
<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/chartjs/Chart.js"/>"></script>
<style>
canvas {
	-moz-user-select: none;
	-webkit-user-select: none;
	-ms-user-select: none;
}
</style>
</head>
<body>

<div style="width: 80%">
	<div>
		<canvas id="canvas" height="350" width="600"></canvas>
	</div>
</div>

<script>
var chartLabels = [];
var chartData1 = [];
var chartData2 = [];

var lineChartData = {
	labels : chartLabels,
	datasets : [ {
		label : "월별 PC 판매량",
		fillColor : "rgba(220,220,220,0.2)",
		strokeColor : "rgba(220,220,220,1)",
		pointColor : "rgba(220,220,220,1)",
		pointStrokeColor : "#fff",
		pointHighlightFill : "#fff",
		pointHighlightStroke : "rgba(220,220,220,1)",
		data : chartData1
	}, {
		label : "월별 모니터 판매량",
		fillColor : "rgba(151,187,205,0.2)",
		strokeColor : "rgba(151,187,205,1)",
		pointColor : "rgba(151,187,205,1)",
		pointStrokeColor : "#fff",
		pointHighlightFill : "#fff",
		pointHighlightStroke : "rgba(151,187,205,1)",
		data : chartData2
	} ]

}

function createChart() {
	var ctx = document.getElementById("canvas").getContext("2d");
	LineChartDemo = Chart.Line(ctx, {
		data : lineChartData,
		options : {
			scales : {
				yAxes : [ {
					ticks : {
						beginAtZero : true
					}
				} ]
			}
		}
	});
}

try {
	$.ajax({
		type : 'POST',
		url : "<c:url value="/json"/>",
		dataType : 'json',
		data : {
			cmd : 'chart',
			subcmd : 'line'
		},
		success : function(result) {

			$.each(result.datas, function(inx, obj) {
				chartLabels.push(obj.month);
				chartData1.push(obj.pc);
				chartData2.push(obj.monitor);

			});

			createChart();

		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert('There is an error : method(group)에 에러가 있습니다.');
		}
	});

} catch (e) {
	alert(e);
}
</script>
</body>
</html>

실행결과

Bar Chart

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>


<script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
<script type="text/javascript" src="<c:url value="/resources/chartjs/Chart.js"/>"></script>
<style>
canvas{
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
}
</style>


<body>
 <div style="width:80%">
        <div>
            <canvas id="canvas" height="350" width="600"></canvas>
        </div>
    </div>
<script>
var chartLabels = [];
var chartData1 = [];
var chartData2 = [];


var lineChartData = {
    labels : chartLabels,
    datasets : [
        {
            label: "월별 PC 판매량",
            fillColor : "rgba(220,220,220,0.2)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(220,220,220,1)",
            data : chartData1 ,
            backgroundColor: [
                "#FF6384",
                "#4BC0C0",
                "#FFCE56",
                "#E7E9ED",
                "#36A2EB"
            ]
        },
        {
            label: "월별 모니터 판매량",
            fillColor : "rgba(151,187,205,0.2)",
            strokeColor : "rgba(151,187,205,1)",
            pointColor : "rgba(151,187,205,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(151,187,205,1)",
            data : chartData2,
            backgroundColor: [
                "#FF6384",
                "#4BC0C0",
                "#FFCE56",
                "#E7E9ED",
                "#36A2EB"
            ]
        }
    ]
 
}

function createChart(){
    var ctx = document.getElementById("canvas").getContext("2d");
    new Chart(ctx, {
        type: 'horizontalBar',
    	data: lineChartData,
    	options: {
            scales: {
            	xAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    });
}

try {
	$.ajax({
		type : 'POST',
		url : "<c:url value="/json"/>",
		dataType : 'json',
		data : {
			cmd : 'chart',
			subcmd : 'line'
		},
		success : function(result) {
		
			    $.each(result.datas, function(inx, obj) {
			        chartLabels.push(obj.month);
			        chartData1.push(obj.pc);
			        chartData2.push(obj.monitor);
			         
			    });
			     
			    createChart();
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert('There is an error : method(group)에 에러가 있습니다.');
		}
	});

} catch (e) {
	alert(e);
}

 
</script>

</body>

</html>

실행결과

Pie Chart

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<!doctype html>
<html>

<head>
    <title>Pie Chart</title>
    <script type="text/javascript" src="<c:url value="/resources/js/jquery-1.12.0.js"/>"></script>
    <script type="text/javascript" src="<c:url value="/resources/chartjs/Chart.js"/>"></script>
    <style>
    canvas{
        -moz-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
    }
    </style>
</head>

<body>
 <div style="width:80%">
        <div>
            <canvas id="canvas" height="350" width="600"></canvas>
        </div>
    </div>
<script>
var chartLabels = [];
var chartData1 = [];
var chartData2 = [];


var PieChartData = {
    labels : chartLabels,
    datasets : [
        {
            label: "월별 PC 판매량",
            fillColor : "rgba(220,220,220,0.2)",
            strokeColor : "rgba(220,220,220,1)",
            pointColor : "rgba(220,220,220,1)",
            pointStrokeColor : "#fff",
            pointHighlightFill : "#fff",
            pointHighlightStroke : "rgba(220,220,220,1)",
            data : chartData1 ,
            backgroundColor: [
                "#FF6384",
                "#4BC0C0",
                "#FFCE56",
                "#E7E9ED",
                "#36A2EB"
            ]
        }
        
        /*,
        {
            label: "월별 모니터 판매량",
            fillColor : "rgba(151,187,205,0.2)",
            strokeColor : "rgba(151,187,205,1)",
            pointColor : "rgba(151,187,205,1)",
            pointStrokeColor : "#aff",
            pointHighlightFill : "#aff",
            pointHighlightStroke : "rgba(151,187,205,1)",
            data : chartData2,
            backgroundColor: [
                "#FF6384",
                "#4BC0C0",
                "#FFCE56",
                "#E7E9ED",
                "#36A2EB"
            ]
        }
        */
    ]
 
}
 
function createChart(){
    var ctx = document.getElementById("canvas").getContext("2d");
    new Chart(ctx, {
        type: 'pie',
    	data: PieChartData,
    	
        options: {
            responsive: true
        }
    });
}

try {
	$.ajax({
		type : 'POST',
		url : "<c:url value="/json"/>",
		dataType : 'json',
		data : {
			cmd : 'chart',
			subcmd : 'line'
		},
		success : function(result) {
		
			    $.each(result.datas, function(inx, obj) {
			        chartLabels.push(obj.month);
			        chartData1.push(obj.pc);
			        chartData2.push(obj.monitor);
			         
			    });
			     
			    createChart();
			
		},
		error : function(XMLHttpRequest, textStatus, errorThrown) {
			alert('There is an error : method(group)에 에러가 있습니다.');
		}
	});

} catch (e) {
	alert(e);
}

 
</script>

</body>

</html>

실행결과

저작자 표시
신고

NanoPi M1 Plus - DHT11 온도 습도 측정

OS/Raspberry Pi 2017.03.28 00:20 Posted by 파란크리스마스

NanoPi M1 Plus - DHT11 온도 습도 측정

출처 : DHT11 Humidity & Temperature Sensor Module | UUGear

C 언어

/*
 *  dht11.c:
 *      Simple test program to test the wiringPi functions
 *      DHT11 test
 */
 
#include <wiringPi.h>
 
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define MAXTIMINGS      85
#define DHTPIN	  7
int dht11_dat[5] = { 0, 0, 0, 0, 0 };
 
void read_dht11_dat() {
	uint8_t laststate       = HIGH;
	uint8_t counter	 = 0;
	uint8_t j	       = 0, i;
	float   f; /* fahrenheit */
 
	dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;
 
	/* pull pin down for 18 milliseconds */
	pinMode( DHTPIN, OUTPUT );
	digitalWrite( DHTPIN, LOW );
	delay( 18 );
	/* then pull it up for 40 microseconds */
	digitalWrite( DHTPIN, HIGH );
	delayMicroseconds( 40 );
	/* prepare to read the pin */
	pinMode( DHTPIN, INPUT );
 
	/* detect change and read data */
	for ( i = 0; i < MAXTIMINGS; i++ ) {
		counter = 0;
		while ( digitalRead( DHTPIN ) == laststate ) {
			counter++;
			delayMicroseconds( 1 );
			if ( counter == 255 ) {
				break;
			}
		}
		laststate = digitalRead( DHTPIN );
 
		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
	 * print it out if data is good
	 */
	if ( (j >= 40) && (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) ) {
		f = dht11_dat[2] * 9. / 5. + 32;
		printf( "Humidity = %d.%d %% Temperature = %d.%d *C (%.1f *F)\n",
			dht11_dat[0], dht11_dat[1], dht11_dat[2], dht11_dat[3], f );
	} else {
		printf( "Data not good, skip\n" );
	}
}
 
int main( void ) {
	printf( "Raspberry Pi wiringPi DHT11 Temperature test program\n" );
 
	if ( wiringPiSetup() == -1 )
		exit( 1 );
 
	while ( 1 ) {
		read_dht11_dat();
		delay( 1000 ); /* wait 1sec to refresh */
	}
 
	return(0);
}

컴파일

# gcc -Wall -o dht11 dht11.c -lwiringPi -lpthread

실행

디버깅 모드 설정

# export WIRINGPI_DEBUG=TRUE

디버깅 모드 해지

# unset WIRINGPI_DEBUG

실행

# ./dht11     
Raspberry Pi wiringPi DHT11 Temperature test program
Data not good, skip
Humidity = 22.0 % Temperature = 23.0 *C (73.4 *F)
Humidity = 22.0 % Temperature = 23.0 *C (73.4 *F)
Data not good, skip
Data not good, skip
Humidity = 22.0 % Temperature = 23.0 *C (73.4 *F)
저작자 표시
신고

Spring MVC - Form 데이터 전달

Programming/Java 2017.03.26 19:51 Posted by 파란크리스마스

기본 Form 데이터 전달

기본 Form 데이터 전달 JSP - /sample/form1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<body>

<form action="<c:url value="/form/form1.do"/>" method="get">
	<input type="text" name="user_id">
	<input type="password" name="password">
	<input type="submit">
</form>

</body>
</html>

기본 Form 데이터 전달 Controller

@Controller
public class FormController {
	
	@RequestMapping(value = "/form/form1.do", method = RequestMethod.GET)
	public String form1(
			@RequestParam("user_id") String user_id, 
			@RequestParam("password") String password,
			ModelMap modelMap) throws Exception 
	{
		System.out.println("user_id = " + user_id + "/" + password);
		return "redirect:/sample/form1.jsp";
	}

파일 업로드 Form 데이터 전달

파일 업로드 Form 데이터 전달 JSP - /sample/form2.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>
<head>
<body>

<form action="<c:url value="/form/form2.do"/>" method="post" enctype="multipart/form-data">
	<input type="text" name="title"><br/>
	<input type="file" name="file1"><br/>
	<input type="file" name="file2"><br/>
	<input type="submit">
</form>

</body>
</html>

파일 업로드 Form 데이터 전달 Controller

@Controller
public class FormController {
	
	@RequestMapping(value = "/form/form2.do", method = RequestMethod.POST)
	public String form2(
			@RequestParam("title") String title, 
			@RequestParam("file1") MultipartFile file1, 
			@RequestParam("file2") MultipartFile file2, 
			ModelMap modelMap) 
	{
		System.out.println("title = " + title);
		
		String uuid_filename1 = fileWrite(file1);
		String uuid_filename2 = fileWrite(file2);
		
		System.out.println(uuid_filename1 + "/" + uuid_filename2);
		
		return "redirect:/sample/form2.jsp";
	}
	
	// 파일 저장 메소드
	private String fileWrite(MultipartFile uploadfile) {
		OutputStream out = null;
		String targetFilename = null;
		try {
			String filePath = "C:/test"; // 설정파일로 뺀다.
			
			// 파일명 얻기
			String fileName = uploadfile.getOriginalFilename();
			
			// 파일의 바이트 정보 얻기
			byte[] bytes = uploadfile.getBytes();
	
			String originalFilename = uploadfile.getOriginalFilename(); // 파일명
			
			// 파일 확장자 추출
			String fileExt = FileUtils.getFileExt(originalFilename);
	
			UUID uuid = UUID.randomUUID();
			targetFilename = uuid.toString() + "." + fileExt.toLowerCase();
	
			String fileFullPath = filePath + "/" + targetFilename; // 파일 전체 경로
			
			// 파일 객체 생성
			File file = new File(fileFullPath);
			// 상위 폴더 존재 여부 확인
			if (!file.getParentFile().exists()) {
				// 상위 폴더가 존재 하지 않는 경우 상위 폴더 생성
				file.getParentFile().mkdirs();
			}
			
			// 파일 아웃풋 스트림 생성
			out = new FileOutputStream(file);
			// 파일 아웃풋 스트림에 파일의 바이트 쓰기
			out.write(bytes);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try { if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); }
		}
		return targetFilename;
	}
}
저작자 표시
신고

Orange PI Zero - pi4j로 PWM 제어

OS/Raspberry Pi 2017.03.25 12:10 Posted by 파란크리스마스

Orange PI Zero - pi4j로 PWM 제어

Orange PI Zero는 하나의 PWM만 지원

배선

Java 소스

import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.OrangePiZeroGpioProvider;
import com.pi4j.wiringpi.Gpio;
import com.pi4j.wiringpi.SoftPwm;

public class SG90PWMMain {

	private static int PIN_NUMBER = 7;

	public static void main(String[] args) throws Exception {
		//
		//GpioFactory.setDefaultProvider(new RaspiGpioProvider(RaspiPinNumberingScheme.BROADCOM_PIN_NUMBERING));
		//GpioFactory.setDefaultProvider(new OrangePiPc2GpioProvider());
		//GpioFactory.setDefaultProvider(new NanoPiNEOAirGpioProvider());
		GpioFactory.setDefaultProvider(new OrangePiZeroGpioProvider());

		// initialize wiringPi library, this is needed for PWM
		Gpio.wiringPiSetup();

		// softPwmCreate(int pin, int value, int range)
		// the range is set like (min=0 ; max=100)
		SoftPwm.softPwmCreate(PIN_NUMBER, 0, 50);
		int counter = 0;
		while (counter < 3) {
			// fade LED to fully ON
			for (int i = 0; i <= 100; i++) {
				// softPwmWrite(int pin, int value)
				// This updates the PWM value on the given pin. The value is
				// checked to be in-range and pins
				// that haven't previously been initialized via softPwmCreate
				// will be silently ignored.
				SoftPwm.softPwmWrite(PIN_NUMBER, i);
				Thread.sleep(25);
			}
			// fade LED to fully OFF
			for (int i = 100; i >= 0; i--) {
				SoftPwm.softPwmWrite(PIN_NUMBER, i);
				Thread.sleep(25);
			}
			counter++;
		}
	}

}

실행

$ sudo java -cp .:pi4j-core.jar:pi4j-gpio-extension.jar SG90PWMMain

실행 영상

저작자 표시
신고

Orange PI Zero GPIO 설치, pi4j

OS/Raspberry Pi 2017.03.25 03:01 Posted by 파란크리스마스

Orange PI Zero GPIO 설치

출처 : WiringOP for Orange pi zero - Beginners - OrangePi - Powered by

현재 pi4j는 Orange PI PC2 지원하지 않아 수정한 jar를 배포합니다.

pi4j-core.jar

$ sudo apt-get install build-essential
$ git clone https://github.com/zhaolei/WiringOP.git -b h3
$ cd WiringOP
$ chmod +x ./build
$ sudo ./build
$ gpio -v
gpio version: 2.20
Copyright (c) 2012-2014 Gordon Henderson
This is free software with ABSOLUTELY NO WARRANTY.
For details type: gpio -warranty
 
Banana Pro Details:
  Type: Banana Pro, Revision: 1.2, Memory: 1024MB, Maker: LeMaker 
orangepi@OrangePizero:~/WiringOP$ gpio readall
 +-----+-----+----------+------+---+-Orange Pi+---+---+------+---------+-----+--+
 | BCM | wPi |   Name   | Mode | V | Physical | V | Mode | Name     | wPi | BCM |
 +-----+-----+----------+------+---+----++----+---+------+----------+-----+-----+
 |     |     |     3.3v |      |   |  1 || 2  |   |      | 5v       |     |     |
 |  12 |   8 |    SDA.0 | ALT5 | 0 |  3 || 4  |   |      | 5V       |     |     |
 |  11 |   9 |    SCL.0 | ALT5 | 0 |  5 || 6  |   |      | 0v       |     |     |
 |   6 |   7 |   GPIO.7 | ALT3 | 0 |  7 || 8  | 0 | ALT3 | TxD3     | 15  | 13  |
 |     |     |       0v |      |   |  9 || 10 | 0 | ALT3 | RxD3     | 16  | 14  |
 |   1 |   0 |     RxD2 | ALT5 | 0 | 11 || 12 | 0 | ALT3 | GPIO.1   | 1   | 110 |
 |   0 |   2 |     TxD2 | ALT5 | 0 | 13 || 14 |   |      | 0v       |     |     |
 |   3 |   3 |     CTS2 | ALT3 | 0 | 15 || 16 | 0 | ALT3 | GPIO.4   | 4   | 68  |
 |     |     |     3.3v |      |   | 17 || 18 | 0 | ALT3 | GPIO.5   | 5   | 71  |
 |  64 |  12 |     MOSI | ALT4 | 0 | 19 || 20 |   |      | 0v       |     |     |
 |  65 |  13 |     MISO | ALT4 | 0 | 21 || 22 | 0 | ALT3 | RTS2     | 6   | 2   |
 |  66 |  14 |     SCLK | ALT4 | 0 | 23 || 24 | 0 | ALT4 | CE0      | 10  | 67  |
 |     |     |       0v |      |   | 25 || 26 | 0 | ALT3 | GPIO.11  | 11  | 21  |
 |  19 |  30 |    SDA.1 | ALT4 | 0 | 27 || 28 | 0 | ALT4 | SCL.1    | 31  | 18  |
 |   7 |  21 |  GPIO.21 | ALT3 | 0 | 29 || 30 |   |      | 0v       |     |     |
 |   8 |  22 |  GPIO.22 | ALT3 | 0 | 31 || 32 | 0 | ALT3 | RTS1     | 26  | 200 |
 |   9 |  23 |  GPIO.23 | ALT3 | 0 | 33 || 34 |   |      | 0v       |     |     |
 |  10 |  24 |  GPIO.24 |  OUT | 0 | 35 || 36 | 0 | ALT3 | CTS1     | 27  | 201 |
 |  20 |  25 |  GPIO.25 |  OUT | 1 | 37 || 38 | 0 | ALT5 | TxD1     | 28  | 198 |
 |     |     |       0v |      |   | 39 || 40 | 0 | ALT5 | RxD1     | 29  | 199 |
 +-----+-----+----------+------+---+----++----+---+------+----------+-----+-----+
 | BCM | wPi |   Name   | Mode | V | Physical | V | Mode | Name     | wPi | BCM |
 +-----+-----+----------+------+---+-Orange Pi+---+------+----------+-----+-----+

C언어 샘플 소스

#include <wiringPi.h>
  
int main()
{
  wiringPiSetup();
  pinMode(7, OUTPUT);
  while(1) {
    digitalWrite(7,HIGH);
    delay(500);
    digitalWrite(7,LOW);
    delay(500);
  }
  return 0;
}

컴파일

$ gcc -Wall -o blink blink.c -lwiringPi -lpthread

실행

$ sudo ./blink

java 샘플 소스

/*
 * #%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 - 2016 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
 * <http://www.gnu.org/licenses/lgpl-3.0.html>.
 * #L%
 */
 
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.OrangePiZeroGpioProvider;
import com.pi4j.io.gpio.OrangePiZeroPin;
import com.pi4j.io.gpio.PinState;
 
/**
 * 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 {

        //GpioFactory.setDefaultProvider(new OrangePiPc2GpioProvider());
        //GpioFactory.setDefaultProvider(new NanoPiNEOAirGpioProvider());
    	GpioFactory.setDefaultProvider(new OrangePiZeroGpioProvider());

        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(OrangePiZeroPin.GPIO_07, "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();
 
        System.out.println("Exiting ControlGpioExample");
    }
}

실행

$ sudo java -cp .:pi4j-core.jar:pi4j-gpio-extension.jar ControlGpioExample

실행결과

저작자 표시
신고

Orange PI Zero

OS/Raspberry Pi 2017.03.25 02:01 Posted by 파란크리스마스

Orange PI Zero

출처 : 스터디메이크 :: 오렌지파이 제로 보드 간단 사용기
Xunlong Orange Pi Zero

vi 설치

$ sudo apt-get install vim

vnc 설치

출처 : Armbian: Access the Remote Desktop of Orange Pi with VNC

vnc 설치

$ sudo apt-get update && apt-get upgrade
$ sudo apt-get install tightvncserver

vnc 사용자 추가

$ su - 
# adduser vnc
Adding user `vnc' ...
Adding new group `vnc' (1001) ...
Adding new user `vnc' (1001) with group `vnc' ...
Creating home directory `/home/vnc' ...
Copying files from `/etc/skel' ...
Enter new UNIX password: 
Retype new UNIX password: 
passwd: password updated successfully
Changing the user information for vnc
Enter the new value, or press ENTER for the default
        Full Name []: VNCuser
        Room Number []: 
        Work Phone []: 
        Home Phone []: 
        Other []: 
Is the information correct? [Y/n] 

vnc 사용자 추가

# gpasswd -a vnc sudo
Adding user vnc to group sudo

vnc 서버 실행

# su - vnc
$ vncserver :1
 
You will require a password to access your desktops.
 
Password: 
Verify:   
Would you like to enter a view-only password (y/n)? 
*** buffer overflow detected ***: vncpasswd terminated
xauth:  file /home/vnc/.Xauthority does not exist
 
New 'X' desktop is OrangePizero:1
 
Creating default startup script /home/vnc/.vnc/xstartup
Starting applications specified in /home/vnc/.vnc/xstartup
Log file is /home/vnc/.vnc/OrangePizero:1.log

Wifi 설정

출처 : 014. Raspberry Pi 라즈베리 파이 - wheezy무선랜 ... - Tsunami - Tistory

$ cd /etc/ifplugd/action.d/
$ sudo mv ifupdown ifupdown.bk
$ sudo cp /etc/wpa_supplicant/ifupdown.sh ./ifupdown

암비안 와이파이 설정

출처 : 오렌지파이 제로 무선인터넷 설정 1.2 암비안 와이파이 설정

$ sudo nmtui

SD 확장

SD 확장전 용량확인

$ sudo fdisk /dev/mmcblk0
Filesystem      Size  Used Avail Use% Mounted on
/dev/root       1.6G  1.2G  349M  78% /
devtmpfs        168M     0  168M   0% /dev
tmpfs           224M     0  224M   0% /dev/shm
tmpfs           224M  8.5M  216M   4% /run
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           224M     0  224M   0% /sys/fs/cgroup
tmpfs           224M  4.0K  224M   1% /tmp
/dev/mmcblk0p1   63M  4.6M   59M   8% /media/boot
tmpfs            45M     0   45M   0% /run/user/107
tmpfs            45M     0   45M   0% /run/user/1000

SD FDisk

orangepi@OrangePizero:~$ sudo fdisk /dev/mmcblk0

Welcome to fdisk (util-linux 2.25.2).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.


Command (m for help): p
Disk /dev/mmcblk0: 7.4 GiB, 7948206080 bytes, 15523840 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x000b04ea

Device         Boot  Start     End Sectors  Size Id Type
/dev/mmcblk0p1       40960  172031  131072   64M  b W95 FAT32
/dev/mmcblk0p2      172032 3514367 3342336  1.6G 83 Linux


Command (m for help): d
Partition number (1,2, default 2): 2

Partition 2 has been deleted.

Command (m for help): n
Partition type
   p   primary (1 primary, 0 extended, 3 free)
   e   extended (container for logical partitions)
Select (default p): p
Partition number (2-4, default 2): 2
First sector (2048-15523839, default 2048): 172032
Last sector, +sectors or +size{K,M,G,T,P} (172032-15523839, default 15523839): 

Created a new partition 2 of type 'Linux' and of size 7.3 GiB.

Command (m for help): w
The partition table has been altered.
Calling ioctl() to re-read partition table.
Re-reading the partition table failed.: Device or resource busy

The kernel still uses the old table. The new table will be used at the next reboot or after you run partprobe(8) or kpartx(8).

orangepi@OrangePizero:~$ sudo shutdown -r now

SD 확장

$ sudo resize2fs /dev/mmcblk0p2
resize2fs 1.42.12 (29-Aug-2014)
Filesystem at /dev/mmcblk0p2 is mounted on /; on-line resizing required
old_desc_blocks = 1, new_desc_blocks = 1
The filesystem on /dev/mmcblk0p2 is now 1918976 (4k) blocks long.

SD 확장 확인

$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/root       7.3G  1.2G  5.8G  17% /
devtmpfs        168M     0  168M   0% /dev
tmpfs           224M     0  224M   0% /dev/shm
tmpfs           224M  8.5M  216M   4% /run
tmpfs           5.0M  4.0K  5.0M   1% /run/lock
tmpfs           224M     0  224M   0% /sys/fs/cgroup
tmpfs           224M  4.0K  224M   1% /tmp
/dev/mmcblk0p1   63M  4.6M   59M   8% /media/boot
tmpfs            45M     0   45M   0% /run/user/107
tmpfs            45M     0   45M   0% /run/user/1000

JDK 설치

$ sudo apt install -t jessie-backports openjdk-8-jre openjdk-8-jre-headless openjdk-8-jdk openjdk-8-jdk-headless ca-certificates-java

JAVA_HOME 환경변수 추가

$ sudo vi /etc/profile

내용 추가 export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-armhf

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-armhf
저작자 표시
신고

NanoPi NEO Air - pi4j로 PWM 제어

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

NanoPi NEO Air - pi4j로 PWM 제어

NanoPi NEO Air는 하나의 PWM만 지원

배선

Java 소스

import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.NanoPiNEOAirGpioProvider;
import com.pi4j.wiringpi.Gpio;
import com.pi4j.wiringpi.SoftPwm;

public class SG90PWMMain {

	private static int PIN_NUMBER = 1;

	public static void main(String[] args) throws Exception {
		//
		//GpioFactory.setDefaultProvider(new RaspiGpioProvider(RaspiPinNumberingScheme.BROADCOM_PIN_NUMBERING));
		//GpioFactory.setDefaultProvider(new OrangePiPc2GpioProvider());
		GpioFactory.setDefaultProvider(new NanoPiNEOAirGpioProvider());

		// initialize wiringPi library, this is needed for PWM
		Gpio.wiringPiSetup();

		// softPwmCreate(int pin, int value, int range)
		// the range is set like (min=0 ; max=100)
		SoftPwm.softPwmCreate(PIN_NUMBER, 0, 50);
		int counter = 0;
		while (counter < 3) {
			// fade LED to fully ON
			for (int i = 0; i <= 100; i++) {
				// softPwmWrite(int pin, int value)
				// This updates the PWM value on the given pin. The value is
				// checked to be in-range and pins
				// that haven't previously been initialized via softPwmCreate
				// will be silently ignored.
				SoftPwm.softPwmWrite(PIN_NUMBER, i);
				Thread.sleep(25);
			}
			// fade LED to fully OFF
			for (int i = 100; i >= 0; i--) {
				SoftPwm.softPwmWrite(PIN_NUMBER, i);
				Thread.sleep(25);
			}
			counter++;
		}
	}

}

실행

# java -cp .:pi4j-core.jar:pi4j-gpio-extension.jar SG90PWMMain

실행 영상

저작자 표시
신고

NanoPi M1 Plus mjpg-streamer

OS/Raspberry Pi 2017.03.22 13:11 Posted by 파란크리스마스

NanoPi M1 Plus mjpg-streamer

출처 : NanoPi NEO Air

패키지 업데이트

패키지 업데이트를 하면 /root/mjpg-streamer 가 생성됨

# apt-get update

mjpg-streamer 컴파일 및 설치

출처 : http://www.lavrsen.dk/svn/motion/tags/3.2.9/picture.c

# cd /root/mjpg-streamer
# make
# sudo make install
make: svnversion: Command not found
install --mode=755 mjpg_streamer /usr/local/bin
install --mode=644 input_uvc.so output_file.so output_udp.so output_http.so input_file.so /usr/local/lib/
install --mode=755 -d /usr/local/www
install --mode=644 -D www/* /usr/local/www

LD_LIBRARY_PATH 경로 추가

# echo "export LD_LIBRARY_PATH=\$LD_LIBRARY_PATH:/usr/local/lib:/usr/local/lib/mjpg-streamer" | sudo tee -a /etc/profile

mjpg-streamer 실행

# ./mjpg_streamer -i "./input_uvc.so -y 1 -r 640x480 -f 30 -q 90 -n" -o "./output_http.so -w ./www"
MJPG Streamer Version: svn rev: 
 i: Using V4L2 device.: /dev/video0
 i: Desired Resolution: 640 x 480
 i: Frames Per Second.: 30
 i: Format............: YUV
 i: JPEG Quality......: 90
 o: www-folder-path...: ./www/
 o: HTTP TCP port.....: 8080
 o: username:password.: disabled
 o: commands..........: enabled

실행 결과

저작자 표시
신고

NanoPi NEO Air - i2c 통신, pi4j, PCA9685

OS/Raspberry Pi 2017.03.22 12:51 Posted by 파란크리스마스

detect I2C chips

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

# apt-get install i2c-tools
# ls /dev/*i2c*
/dev/i2c-0
# i2cdetect -y 0
     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 -- -- -- -- -- -- --    

PCA9685 제어

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.NanoPiNEOAirGpioProvider;
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 {
	
	public static final int SERVO_DURATION_MIN = 600;
	public static final int SERVO_DURATION_NEUTRAL = 1500;
	public static final int SERVO_DURATION_MAX = 2400;
	
	private static PCA9685Gpio instance = null;
	
	private PCA9685GpioProvider gpioProvider = null;
	
	// sudo java -cp .:pi4j-core.jar:pi4j-gpio-extension.jar PCA9685Gpio
	
	private PCA9685Gpio() throws IOException, UnsupportedBusNumberException {		
		
		//GpioFactory.setDefaultProvider(new BPIM2PGpioProvider());
		GpioFactory.setDefaultProvider(new NanoPiNEOAirGpioProvider());
		
		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_0);
		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_01, SERVO_DURATION_NEUTRAL);
		Thread.sleep(200);
		
		for (int i=SERVO_DURATION_MIN; i<=SERVO_DURATION_MAX; i+=30) {
			test.setPwm(PCA9685Pin.PWM_00, i);
			Thread.sleep(200);
		}
		
		for (int i=SERVO_DURATION_MAX; i>=(int)(SERVO_DURATION_MIN+(SERVO_DURATION_MAX-SERVO_DURATION_MIN)/2); i-=30) {
			test.setPwm(PCA9685Pin.PWM_00, i);
			Thread.sleep(200);
		}
				
		for (int i=SERVO_DURATION_MIN; i<=SERVO_DURATION_MAX; i+=30) {
			test.setPwm(PCA9685Pin.PWM_01, i);
			Thread.sleep(200);
		}
		
		for (int i=SERVO_DURATION_MAX-200; i>=(int)(SERVO_DURATION_MIN+(SERVO_DURATION_MAX-SERVO_DURATION_MIN)/2); i-=30) {
			test.setPwm(PCA9685Pin.PWM_01, i);
			Thread.sleep(200);
		}
		
		test.shutdown();

	}
	
}

실행

# java -cp .:pi4j-core.jar:pi4j-gpio-extension.jar PCA9685Gpio

실행 결과

저작자 표시
신고

NanoPi NEO Air - WiringNP, pi4j

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

NanoPi NEO Air - WiringNP, pi4j

출처 : NanoPi NEO Air

현재 pi4j는 NanoPi NEO Air을 지원하지 않아 수정한 jar를 배포합니다.

pi4j-core.jar

# git clone git://github.com/wertyzp/WiringNP
# cd WiringNP
# sh ./build

GPIO 설치 확인

# gpio -v
gpio version: 2.20
Copyright (c) 2012-2014 Gordon Henderson
This is free software with ABSOLUTELY NO WARRANTY.
For details type: gpio -warranty

Banana Pro Details:
  Type: Model A, Revision: 1.2, Memory: 1024MB, Maker: LeMaker 
# gpio readall
 +-----+-----+----------+------+---+-NanoPI M1+---+------+----------+-----+-----+
 | BCM | wPi |   Name   | Mode | V | Physical | V | Mode | Name     | wPi | BCM |
 +-----+-----+----------+------+---+----++----+---+------+----------+-----+-----+
 |     |     |     3.3v |      |   |  1 || 2  |   |      | 5v       |     |     |
 |  12 |   8 |    SDA.0 | ALT5 | 0 |  3 || 4  |   |      | 5V       |     |     |
 |  11 |   9 |    SCL.0 | ALT5 | 0 |  5 || 6  |   |      | 0v       |     |     |
 | 203 |   7 |   GPIO.7 |  OUT | 1 |  7 || 8  | 0 | ALT5 | TxD3     | 15  | 198 |
 |     |     |       0v |      |   |  9 || 10 | 0 | ALT5 | RxD3     | 16  | 199 |
 |   0 |   0 |     RxD2 | ALT5 | 0 | 11 || 12 | 0 | OFF  | GPIO.1   | 1   | 6   |
 |   2 |   2 |     TxD2 | ALT5 | 0 | 13 || 14 |   |      | 0v       |     |     |
 |   3 |   3 |     CTS2 | ALT5 | 0 | 15 || 16 | 0 | OFF  | GPIO.4   | 4   | 200 |
 |     |     |     3.3v |      |   | 17 || 18 | 0 | OFF  | GPIO.5   | 5   | 201 |
 |  64 |  12 |     MOSI | ALT4 | 0 | 19 || 20 |   |      | 0v       |     |     |
 |  65 |  13 |     MISO | ALT4 | 0 | 21 || 22 | 0 | ALT5 | RTS2     | 6   | 1   |
 |  66 |  14 |     SCLK | ALT4 | 0 | 23 || 24 | 0 | ALT4 | CE0      | 10  | 67  |
 |     |     |       0v |      |   | 25 || 26 | 0 | OFF  | GPIO.11  | 11  | 17  |
 |  19 |  30 |    SDA.1 | ALT5 | 0 | 27 || 28 | 0 | ALT5 | SCL.1    | 31  | 18  |
 |  20 |  21 |  GPIO.21 | ALT5 | 0 | 29 || 30 |   |      | 0v       |     |     |
 |  21 |  22 |  GPIO.22 | ALT5 | 0 | 31 || 32 | 0 | OFF  | RTS1     | 26  | 7   |
 |   8 |  23 |  GPIO.23 |  OUT | 0 | 33 || 34 |   |      | 0v       |     |     |
 |  16 |  24 |  GPIO.24 | ALT4 | 0 | 35 || 36 | 0 | ALT4 | CTS1     | 27  | 13  |
 |   9 |  25 |  GPIO.25 |  OFF | 0 | 37 || 38 | 0 | OUT  | TxD1     | 28  | 15  |
 |     |     |       0v |      |   | 39 || 40 | 0 | ALT4 | RxD1     | 29  | 14  |
 +-----+-----+----------+------+---+----++----+---+------+----------+-----+-----+
 | BCM | wPi |   Name   | Mode | V | Physical | V | Mode | Name     | wPi | BCM |
 +-----+-----+----------+------+---+-NanoPI M1+---+------+----------+-----+-----+

 +-----+----NanoPI M1 Debug UART---+----+
 | BCM | wPi |   Name   | Mode | V | Ph |
 +-----+-----+----------+------+---+----+
 |     |     |       0v |      |   | 41 |
 |     |     |       5v |      |   | 42 |
 |   4 |  32 |   GPIO.4 | ALT5 | 0 | 43 |
 |   5 |  33 |   GPIO.5 | ALT5 | 0 | 44 |
 +-----+-----+----------+------+---+----+

C언어 샘플 소스

#include <wiringPi.h>

int main()
{
  wiringPiSetup();
  pinMode(7, OUTPUT);
  while(1) {
    digitalWrite(7,HIGH);
    delay(500);
    digitalWrite(7,LOW);
    delay(500);
  }
  return 0;
}

컴파일

# gcc -Wall -o blink blink.c -lwiringPi -lpthread

실행

# ./blink

java 샘플 소스

/*
 * #%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 - 2016 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
 * <http: www.gnu.org="" licenses="" lgpl-3.0.html="">.
 * #L%
 */
 
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.NanoPiNEOAirGpioProvider;
import com.pi4j.io.gpio.NanoPiNEOAirPin;
import com.pi4j.io.gpio.PinState;
 
/**
 * 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 {

        //GpioFactory.setDefaultProvider(new OrangePiPc2GpioProvider());
        GpioFactory.setDefaultProvider(new NanoPiNEOAirGpioProvider());

        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(NanoPiNEOAirPin.GPIO_07, "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();
 
        System.out.println("Exiting ControlGpioExample");
    }
}

실행

# java -cp .:pi4j-core.jar:pi4j-gpio-extension.jar ControlGpioExample

실행결과


저작자 표시
신고

NanoPi NEO Air

OS/Raspberry Pi 2017.03.21 23:41 Posted by 파란크리스마스

NanoPi NEO Air

출처 : NanoPi NEO Air

시리얼 연결

  • Debug Port(UART0)

RX | TX | 5v | GND

터미널 연결

기본 로그인 아이디, 패스워드

"root" / "fa"

Wifi 설정

# vi /etc/wpa_supplicant/wpa_supplicant.conf 

wpa_supplicant.conf

network={
        ssid="ssid1"
        psk="YourWiFiPassword"
}

network={
        ssid="ssid2"
        psk="YourWiFiPassword"
}

무선랜카드 다시 시작

# ifdown wlan0
Killed old client process
Internet Systems Consortium DHCP Client 4.3.3
Copyright 2004-2015 Internet Systems Consortium.
All rights reserved.
For info, please visit https://www.isc.org/software/dhcp/
 
Listening on LPF/wlan0/94:a1:a2:94:d1:a0
Sending on   LPF/wlan0/94:a1:a2:94:d1:a0
Sending on   Socket/fallback
DHCPRELEASE on wlan0 to 192.168.0.1 port 67 (xid=0x2f0e629b)
# ifup wlan0
Internet Systems Consortium DHCP Client 4.3.3
Copyright 2004-2015 Internet Systems Consortium.
All rights reserved.
For info, please visit https://www.isc.org/software/dhcp/
 
Listening on LPF/wlan0/94:a1:a2:94:d1:a0
Sending on   LPF/wlan0/94:a1:a2:94:d1:a0
Sending on   Socket/fallback
DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 3 (xid=0xc921c22e)
DHCPDISCOVER on wlan0 to 255.255.255.255 port 67 interval 6 (xid=0xc921c22e)
DHCPREQUEST of 192.168.0.59 on wlan0 to 255.255.255.255 port 67 (xid=0x2ec221c9)
DHCPOFFER of 192.168.0.59 from 192.168.0.1
DHCPACK of 192.168.0.59 from 192.168.0.1
bound to 192.168.0.59 -- renewal in 2738 seconds.

패키지 업데이트

# apt-get update

Bluetooth

# apt-get install bluetooth bluez obexftp openobex-apps python-gobject ussp-push time bc

How to burn Linux image to eMMC

출처 : How to burn Linux image to eMMC
bpi-copy command

# fdisk -l
Disk /dev/mmcblk0: 7.4 GiB, 7948206080 bytes, 15523840 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0xbac8c0ae
 
Device         Boot  Start      End  Sectors  Size Id Type
/dev/mmcblk0p1       49152   131071    81920   40M 83 Linux
/dev/mmcblk0p2      131072 15523839 15392768  7.3G 83 Linux
 

Disk /dev/mmcblk1: 7.3 GiB, 7818182656 bytes, 15269888 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
 

Disk /dev/mmcblk1boot1: 4 MiB, 4194304 bytes, 8192 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
 

Disk /dev/mmcblk1boot0: 4 MiB, 4194304 bytes, 8192 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

이미지 복원

이미지 복원이 완료되면 SD 메모리를 제거하고 재부팅

# dd if=nanopi-air-ubuntu-core-qte-sd4g-20170220.img of=/dev/mmcblk1 bs=10MB
389+1 records in
389+1 records out
3899999232 bytes (3.9 GB, 3.6 GiB) copied, 346.862 s, 11.2 MB/s

OpenJDK 1.8 설치

# apt-get install openjdk-8-jdk

JAVA_HOME 환경변수 추가

# vi /etc/profile

내용 추가 export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-armhf

export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-armhf
저작자 표시
신고

Orange PI PC2 GPIO 설치, pi4j

OS/Raspberry Pi 2017.03.17 01:53 Posted by 파란크리스마스

Orange PI PC2 GPIO 설치

출처 : This is a modified WiringPi for OrangePi. We call it WiringOP. Test fo Orangepi pc
OrangePi-PCを使ってみる WiringPiとWiringOP
Orange PI PC 2 GPIO доступ через sysfs

현재 pi4j는 Orange PI PC2 지원하지 않아 수정한 jar를 배포합니다.

pi4j-core.jar

$ git clone https://github.com/kazukioishi/WiringOP.git -b h5
$ cd WiringOP
$ chmod +x ./build
$ sudo ./build
$ gpio -v
gpio version: 2.20
Copyright (c) 2012-2014 Gordon Henderson
This is free software with ABSOLUTELY NO WARRANTY.
For details type: gpio -warranty
 
Banana Pro Details:
  Type: Banana Pro, Revision: 1.2, Memory: 1024MB, Maker: LeMaker 
$ gpio readall
 +-----+-----+----------+------+---+-Orange Pi+---+---+------+---------+-----+--+
 | BCM | wPi |   Name   | Mode | V | Physical | V | Mode | Name     | wPi | BCM |
 +-----+-----+----------+------+---+----++----+---+------+----------+-----+-----+
 |     |     |     3.3v |      |   |  1 || 2  |   |      | 5v       |     |     |
 |  12 |   8 |    SDA.0 | ALT5 | 0 |  3 || 4  |   |      | 5V       |     |     |
 |  11 |   9 |    SCL.0 | ALT5 | 0 |  5 || 6  |   |      | 0v       |     |     |
 |   6 |   7 |   GPIO.7 | ALT3 | 0 |  7 || 8  | 0 | ALT5 | TxD3     | 15  | 13  |
 |     |     |       0v |      |   |  9 || 10 | 0 | ALT5 | RxD3     | 16  | 14  |
 |   1 |   0 |     RxD2 | ALT5 | 0 | 11 || 12 | 0 | ALT3 | GPIO.1   | 1   | 110 |
 |   0 |   2 |     TxD2 | ALT5 | 0 | 13 || 14 |   |      | 0v       |     |     |
 |   3 |   3 |     CTS2 | ALT5 | 0 | 15 || 16 | 0 | ALT3 | GPIO.4   | 4   | 68  |
 |     |     |     3.3v |      |   | 17 || 18 | 0 | ALT3 | GPIO.5   | 5   | 71  |
 |  64 |  12 |     MOSI | ALT4 | 0 | 19 || 20 |   |      | 0v       |     |     |
 |  65 |  13 |     MISO | ALT0 | 0 | 21 || 22 | 0 | ALT5 | RTS2     | 6   | 2   |
 |  66 |  14 |     SCLK | ALT4 | 0 | 23 || 24 | 0 | ALT4 | CE0      | 10  | 67  |
 |     |     |       0v |      |   | 25 || 26 | 0 | ALT3 | GPIO.11  | 11  | 21  |
 |  19 |  30 |    SDA.1 | ALT4 | 0 | 27 || 28 | 0 | ALT4 | SCL.1    | 31  | 18  |
 |   7 |  21 |  GPIO.21 | ALT3 | 0 | 29 || 30 |   |      | 0v       |     |     |
 |   8 |  22 |  GPIO.22 | ALT3 | 0 | 31 || 32 | 0 | ALT5 | RTS1     | 26  | 200 |
 |   9 |  23 |  GPIO.23 | ALT3 | 0 | 33 || 34 |   |      | 0v       |     |     |
 |  10 |  24 |  GPIO.24 | ALT3 | 0 | 35 || 36 | 0 | ALT5 | CTS1     | 27  | 201 |
 |  20 |  25 |  GPIO.25 |  OUT | 1 | 37 || 38 | 0 | ALT5 | TxD1     | 28  | 198 |
 |     |     |       0v |      |   | 39 || 40 | 0 | ALT5 | RxD1     | 29  | 199 |
 +-----+-----+----------+------+---+----++----+---+------+----------+-----+-----+
 | BCM | wPi |   Name   | Mode | V | Physical | V | Mode | Name     | wPi | BCM |
 +-----+-----+----------+------+---+-Orange Pi+---+------+----------+-----+-----+

C언어 샘플 소스

#include <wiringpi.h>
 
int main()
{
  wiringPiSetup();
  pinMode(7, OUTPUT);
  while(1) {
    digitalWrite(7,HIGH); 
    delay(500);
    digitalWrite(7,LOW); 
    delay(500);
  }
  return 0;
}

컴파일

$ gcc -Wall -o blink blink.c -lwiringPi -lpthread

실행

$ sudo ./blink
wiringPi: wiringPiSetup called
piboardRev: Hardware string: Hardware   : sun50iw2
Hardware:Hardware       : sun50iw2
piboardRevH3:  3
piboardRev: Hardware string: Hardware   : sun50iw2
Hardware:Hardware       : sun50iw2
piboardRevH3:  3
piboardRev: Hardware string: Hardware   : sun50iw2
Hardware:Hardware       : sun50iw2
piboardId: Revision string: 0000
pinMode,1947,pin:7,mode:1
func:sunxi_set_gpio_mode pin:6, MODE:1 bank:0 index:6 phyaddr:0x1c20800
read reg val: 0x71222222 offset:24
Out mode ready set val: 0x71222222
Out mode set over reg val: 0x71222222
digitalWrite,2270
func:sunxi_digitalWrite pin:6, value:1 bank:0 index:6 phyaddr:0x1c20810
befor write reg val: 0x100040,index:6
HIGH val set over reg val: 0x100040
digitalWrite,2270
func:sunxi_digitalWrite pin:6, value:0 bank:0 index:6 phyaddr:0x1c20810
befor write reg val: 0x100040,index:6
LOW val set over reg val: 0x100000
digitalWrite,2270
func:sunxi_digitalWrite pin:6, value:1 bank:0 index:6 phyaddr:0x1c20810
befor write reg val: 0x100000,index:6
HIGH val set over reg val: 0x100040
digitalWrite,2270
func:sunxi_digitalWrite pin:6, value:0 bank:0 index:6 phyaddr:0x1c20810
befor write reg val: 0x100040,index:6
LOW val set over reg val: 0x100000
digitalWrite,2270
func:sunxi_digitalWrite pin:6, value:1 bank:0 index:6 phyaddr:0x1c20810
befor write reg val: 0x100000,index:6
HIGH val set over reg val: 0x100040

java 샘플 소스

import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.OrangePiPc2GpioProvider;
import com.pi4j.wiringpi.Gpio;

public class Blink {

	public static void main(String[] args) throws InterruptedException {
		
		GpioFactory.setDefaultProvider(new OrangePiPc2GpioProvider());

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

		Gpio.pinMode(7, Gpio.OUTPUT);
		while (true) {
			Gpio.digitalWrite(7, Gpio.HIGH);
			Gpio.delay(500);
			Gpio.digitalWrite(7, Gpio.LOW);
			Gpio.delay(500);
		}
	}
}

실행

$ sudo java -cp .:pi4j-core.jar:pi4j-gpio-extension.jar Blink

실행결과

저작자 표시
신고


 

티스토리 툴바