'분류 전체보기'에 해당되는 글 107건

  1. 2014.07.13 아두이노용 씨리얼 테스트 코드
  2. 2014.06.09 How to process argument between js(html5) and cordova 3.x
  3. 2014.06.08 How to make cordova 3.X plugin (only android)
  4. 2014.06.03 msp430 launchpad pin 접근하기
  5. 2014.06.03 RN42 블루트스 모듈 사용기
  6. 2014.05.02 node.js 로 raspberry sound system 만들기
  7. 2014.04.30 node.js file uploader (파일 업로더 만들기)
  8. 2014.04.22 how to arduino wifi-shield firmware upgrade (for macOS 10.9)
  9. 2014.04.05 querySelector 팁 몇가지
  10. 2014.03.08 우분투에 오라클 클라이언트 인터페이스 설치하기(OCI)

아두이노용 씨리얼 테스트 코드

|

안드로이드와 하거나 다른 기기와 테스트할때 가능함

아두이노쪽에서 주기적으로 틱이 날라오고 메씨지를 보낼경우 에코해줌





/* Copyright 2012 Google Inc.
 *
 * This library 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 2.1 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
 * USA.
 *
 * Project home page: http://code.google.com/p/usb-serial-for-android/
 */

// Sample Arduino sketch for use with usb-serial-for-android.
// Prints an ever-increasing counter, and writes back anything
// it receives.

static int counter = 0;
void setup() {
  Serial.begin(115200);
}

void loop() {
  Serial.print("Tick #");
  Serial.print(counter++, DEC);
  Serial.print("\n");

  if (Serial.peek() != -1) {
    Serial.print("Read: ");
    do {
      Serial.print((char) Serial.read());
    } while (Serial.peek() != -1);
    Serial.print("\n");
  }
  delay(1000);
}



And

How to process argument between js(html5) and cordova 3.x

|

CordovaPlugin 에서 상속받은 클래스의 멤버함수인  excute의 json을 처리할수 있는 스펙은 아래와 같습니다.


public boolean execute(String action, JSONArray args,

final CallbackContext callbackContext)


1. js 에서 넘어온 인자 받기

args 에 배열의 첫번째로 넘겨온 json object를 얻으려면 아래 와 같이 해줍니다.


JSONObject json = args.getJSONObject(0);


get 함수로 각각의 json object 의 멤버변수들을 얻어올수 있습니다.


Log.d(TAG, "pi : " + json.get("pi"));

Log.d(TAG, "number : " + json.get("number"));

Log.d(TAG, "msg : " + json.get("msg"));


각 변수들은 기본적으로 String 형으로 받아지기 때문에 int 형을 처리 해주려면 타입 캐스팅을 해줍니다.


(Integer) json.get("number") + 1 


2. js 로 결과값을 인자로 넘겨주기


먼저 넘겨줄 빈 json 오브잭트를 만듭니다.

JSONObject resultJSON = new JSONObject();


put 함수로 값을 체워 넣습니다.

resultJSON.put("result", "ok");

resultJSON.put("msg", "json echo!!");


전송하기전에 먼저 PluginResult 객체에 담아줍니다.

PluginResult plugin_result = new PluginResult(Status.OK, resultJSON);


콜백컨텍스트의 sendPluginResult 함수로 js 측으로 결과 값을 전달합니다.

callbackContext.sendPluginResult(plugin_result);


3. 예제 실행법


plugin_sample.zip

 파일을 다운받습니다.


코도바 프로잭트를 생성하고  안드로이드 플랫폼을 추가합니다.

압축을 푸시고 로컬에서 다음과 같이 플러그인을 추가 합니다.( 플러그인의 경로가 ../plugin_sample/echo 이라고 가정)

cordova plugin add ../plugin_sample/echo


js 쪽 예제는 첨부된 파일의 index.html을 참고 하시면됩니다.



'html5' 카테고리의 다른 글

cordova-pulgin-whitelist 사용법  (0) 2015.11.29
crosswalk 사용기 1차  (0) 2015.11.22
How to make cordova 3.X plugin (only android)  (0) 2014.06.08
querySelector 팁 몇가지  (0) 2014.04.05
cordova 3.X 사용방법정리  (0) 2014.01.27
And

How to make cordova 3.X plugin (only android)

|

1. 플러그인 저장폴더 만들기(저장소)



다음과 같이 폴더를 구성합니다.



이 연습용 플러인 이름은 echo 입니다.


이렇게 만들어진 플러그인은 echo 폴더를 그대로 업로드 하는 방식으로 웹서버나 git을 통해서 간단하게 배포될수있습니다.


플러그인전체 구성을 정의해주는 plugin.xml 파일을 만들어 보겠습니다.


<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"

        xmlns:rim="http://www.blackberry.com/ns/widgets"

        xmlns:android="http://schemas.android.com/apk/res/android"

        id="플러그인고유식별자"

        version="0.0.1">

    <name>플러그인이름</name>

    <description>플러그인설명</description>

    <license>Apache 2.0</license>

    <keywords>플러그인 검섹키워드</keywords>


    <!-- android -->

    <platform name="android">

        <config-file target="res/xml/config.xml" parent="/*">

            <feature name="모듈이름(자바클래스이름)" >

                <param name="android-package" value="패키지이름을포함한모듈이름"/>

            </feature>

        </config-file>


        <source-file src="소스파일경로(pluin.xml파일이있는폴더기준)" target-dir="타겟경로(코도바프로잭트루트기준)" />

    </platform>

</plugin>


echo 플러그인을 위한 pulgin.xml 을 다음과 같이 만들어 보았습니다.


<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"

        xmlns:rim="http://www.blackberry.com/ns/widgets"

        xmlns:android="http://schemas.android.com/apk/res/android"

        id="com.gunpower.cordova.echo"

        version="0.0.1">

    <name>echo</name>

    <description>Cordova echo Plugin</description>

    <license>Apache 2.0</license>

    <keywords>cordova,echo</keywords>


    <!-- android -->

    <platform name="android">

        <config-file target="res/xml/config.xml" parent="/*">

            <feature name="Echo" >

                <param name="android-package" value="com.gunpower.cordova.echo.Echo"/>

            </feature>

        </config-file>


        <source-file src="src/android/Echo.java" target-dir="src/com/gunpower/cordova/echo" />

    </platform>

</plugin>



pluign.xml 파일에서 정의한 대로 src/android/Echo.java 경로로 파일을 작성합니다.


package com.gunpower.cordova.echo;


import org.apache.cordova.CallbackContext;

import org.apache.cordova.CordovaArgs;

import org.apache.cordova.CordovaInterface;

import org.apache.cordova.CordovaPlugin;

import org.apache.cordova.CordovaWebView;

import org.json.JSONArray;

import org.json.JSONException;


import android.util.Log;


public class Echo extends CordovaPlugin {

public static final String TAG = "Echo";


@Override

public void initialize(CordovaInterface cordova, CordovaWebView webView) {

// TODO Auto-generated method stub

super.initialize(cordova, webView);

Log.d(TAG, "echo pluin initialize");

}


@Override

public boolean execute(String action, String rawArgs,

CallbackContext callbackContext) throws JSONException {

// TODO Auto-generated method stub

return super.execute(action, rawArgs, callbackContext);

}


@Override

public boolean execute(String action, JSONArray args,

CallbackContext callbackContext) throws JSONException {

// TODO Auto-generated method stub

final String result = args.isNull(0) ? null : args.getString(0);

        

        if ("echo".equals(action)) {

        //인자 다시 자바스크립트로 전달하기 

            callbackContext.success(result);

            return true;

        } 

        

return super.execute(action, args, callbackContext);

}


@Override

public boolean execute(String action, CordovaArgs args,

CallbackContext callbackContext) throws JSONException {

// TODO Auto-generated method stub

return super.execute(action, args, callbackContext);

}


}



이상으로 플러그인 저장소가 만들어졌습니다.


2. 프로잭트에 플러그인 설치


cordova create myapp com.gbox.myapp myapp

cordova platform add android


myapp 으로 코도바 프로잭트를 만들고 플랫폼으로 안드로이드를 추가 합니다.




커멘드라인툴로 다음과같이 명령어를 주어서 플러그인을 myapp 프로잭트에 추가합니다.


cd myapp

cordova plugin add ../echo


3. 플러그인사용하기


cordova.exec 함수를 사용합니다.



자바스크립트쪽에서 cordova.exec 함수를 써서 Echo플러그인(service)의 echo 함수(action)를 호출하는 예 입니다.


cordova.exec(function(param) {

            console.log(param);

        }, function(err) {

            console.log('Nothing to echo.');

        }, "Echo", "echo", ['hello plugin!']);











And

msp430 launchpad pin 접근하기

|


런치페드는 아두이노와는 다르게 포트번호게 P1.1 이런식으로 표기 되어 있습니다.







 P1.6 , P2.0 으로 표시된 핀들에 연결을 했습니다.


 p1.6 번으로 표기된 핀은 P1_6 으로...

 p2.0 번으로 표기된 핀은 P2_0 으로 접근하실수 있습니다.


예>

 pinMode(P1_6,OUTPUT);


테스트 동영상입니다.





예제소스>


/*

  DigitalReadSerial with on-board Pushbutton

  Reads a digital input on pin 5, prints the result to the serial monitor 

 

  Harware Required:

  * MSP-EXP430G2 LaunchPad

  

  This example code is in the public domain.

 */


int pushButton = P1_1;

int pushButton2 = P2_1;


int testLed = P1_6;

int testLed2 = P2_0;


// the setup routine runs once when you press reset:

void setup() {

  // initialize serial communication at 9600 bits per second:

  Serial.begin(9600); // msp430g2231 must use 4800

  // make the on-board pushbutton's pin an input pullup:

  pinMode(pushButton, INPUT_PULLUP);

  pinMode(pushButton2, INPUT_PULLUP);

  

  pinMode(testLed,OUTPUT);

  pinMode(testLed2,OUTPUT);

}


// the loop routine runs over and over again forever:

void loop() {

  // read the input pin:

  int buttonState = digitalRead(pushButton);

  // print out the state of the button:

  

  if(buttonState) {

    digitalWrite(testLed, HIGH); 

  }

  else {

    digitalWrite(testLed, LOW); 

  }


  if(digitalRead(pushButton2)) {

    digitalWrite(testLed2, HIGH); 

  }

  else {

    digitalWrite(testLed2, LOW); 

  }

  

  Serial.println(buttonState);

  delay(1);        // delay in between reads for stability

}






And

RN42 블루트스 모듈 사용기

|






초기 설정은 다음과 같습니다.




블루투스를 잡으신 다음에 연결 테스트 하실려면 이와 같이 설정 해줍니다.


명령어 관련 문서는....

bluetooth_cr_UG-v1.0r.pdf





UART 에 연결하실때에는 반드시 3.3 V 에 연결하셔야하며 rx,tx 는 서로 교차되어 연결해주어야합니다.









And

node.js 로 raspberry sound system 만들기

|

1. 싸운드 환경 설치


다음과 같은 순서로 유틸리티들을 설치합니다.

  • The ALSA utilities:
    sudo apt-get install alsa-utils
  • MP3 tools:
    sudo apt-get install mpg321
  • WAV to MP3 conversion tool:
    sudo apt-get install lame


사운드 드라이버를 로드해줍니다.


  • sudo modprobe snd-bcm2835

제대로 설치 됐는지 확인하려면


  • sudo lsmod | grep 2835

출력디바이스를 지정합니다.

Select the output device for sound (0=auto, 1=analog, 2=HDMI):

  • sudo amixer cset numid=3 1

1번은 일반핀입니다. 2번은 hdhi단자로 출력하고싶을때 사용합니다.


혹시 소리가 나지 않앗다면 다음과 같이해서 볼륨을 조절합니다.


sudo amixer cset numid=1 n



n 이 볼륨값입니다. 퍼센테이지로 0~100%  사의 값을 넣어 주거나 0~400사이 값을 넣어줄수있습니다.


테스트는 다음과 같이 합니다. 커멘드 창에서 아래 명령어들을 입력 해봅니다.


  • aplay /usr/share/sounds/alsa/Front_Center.wav
  • speaker-test -t sine -f 440 -c 2 -s 1
  • mpg321 “Mannish Boy.mp3″

aplay 로는 wav 만 연주 가능합니다. mp3 는 mpg321 로 하셔야합니다.


기타 사항입니다.


It you get the following error message:

  • ALSA lib pcm.c:2217:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.front

Edit the file /usr/share/alsa/alsa.conf:

  • sudo nano /usr/share/alsa/alsa.conf
  • change the line “pcm.front cards.pcm.front” to “pcm.front cards.pcm.default”

If you are using HDMI and cannot hear any audio at all change the following PIconfiguration setting:

  • edit the RasPI configuration file:
    sudo nano /boot/config.txt
  • uncomment the line:
    hdmi_drive=2
  • save the file and reboot the PI


출처 : 

http://cagewebdev.com/index.php/raspberry-pi-getting-audio-working/

http://www.raspberrypi-spy.co.uk/2013/06/raspberry-pi-command-line-audio/




2. 노드 플러그인 설치


alsa 개발 sdk 를 먼저 설치합니다.

sudo apt-get install libasound2-dev

npm install -g lame
npm install -g wav
npm install -g speaker


출처 :

http://nmecdesign.com/blog/audio-on-the-raspberry-pi-with-node-js/


3. 예제


var lame = require(theApp.module_path +'lame');

var wav = require(theApp.module_path +'wav');

var Speaker = require(theApp.module_path + 'speaker');


var wav_obj = {

                    file : fs.createReadStream('./effectsound/hit1.wav' ),

                    reader : new wav.Reader()

                };


                wav_obj.reader.on('format',function(format) {


                    //console.log(format);

                    wav_obj.speaker = new Speaker(format);


                    wav_obj.reader.pipe(wav_obj.speaker);




                });


                wav_obj.file.pipe(wav_obj.reader);


mp 의 경우는 reader stream을 lame 으로 하면된다.



And

node.js file uploader (파일 업로더 만들기)

|

2014.4월 현재 나와있는 예제들은 express가 버전업되면서 모두 제대로 동작 하지않습니다.


formidable 플러그인을 이용한 방법이 있습니다.


https://github.com/felixge/node-formidable


자세한 내용은 위의 주소에서 확인할수 있습니다.


대략내용은 파일업로드를 위하여 만든 플러그인이라고 합니다.


참고자료 :

http://helloraspberrypi.blogspot.kr/2014/04/upload-file-using-nodejs-with-formidable.html




-소스-

/*

<!-- index.html 파일예 --->

<form method="post" enctype="multipart/form-data" action="http://localhost:8081/file-upload">

    <input type="file" name="thumbnail">

    <input type="submit">

</form>

*/

var theApp = {

    version : '0.2',

    module_path : '',

    port : 8081


};

//command line argument parse

process.argv.forEach(function(val, index, array) {


    //console.log(index + ': ' + val);


    if(val.indexOf('=') > 0) {


        var tokens = val.split('=');


        switch (tokens[0]) {

            case 'port':

                theApp.port = parseInt(tokens[1]);

                break;

            case 'module_path':

                theApp.module_path = tokens[1];

                break;

        }

    }

});


//console.log(theApp);


// run the command to install formidable

// $ npm install formidable

var formidable = require( theApp.module_path +'formidable');

var http = require('http');

var util = require('util');

var fs = require('fs');

var os = require('os');

var UrlParser = require('url');




var app = http.createServer(

    function(req, res){

        switch(req.method){

            case 'GET':

                process_get(req, res);

                break;

            case 'POST':

                process_post(req, res);

                break;

        }

    }

);

app.listen(theApp.port);


console.log('tiny upload server v ' + theApp.version );

console.log('  start port : '+ theApp.port + ', ready ok!');


//Display my IP

(function get_MyIP() {

    var networkInterfaces = os.networkInterfaces();


    for (var interface in networkInterfaces) {


        networkInterfaces[interface].forEach(

            function(details){


                if (details.family=='IPv4'

                    && details.internal==false) {

                    console.log(interface, details.address);

                }

            });

    }

})();


//get 처리 해주기

function process_get(req, res){


    var result = UrlParser.parse(req.url,true);


    switch (result.pathname) {

        case '/test':

            fs.readFile(__dirname + '/index.html',

                function (err, data) {

                    if (err) {

                        res.writeHead(500);

                        return res.end('Error loading index.html');

                    }


                    res.writeHead(200);

                    res.end(data);

                });

            break;

        default :

            break;

    }



}


function process_post(req, res){


    var form = new formidable.IncomingForm();


    form.uploadDir = "./uploads"; //업로드할위치 지정

    form.keepExtensions = true; //확장자 이름 써주기


    form.parse(req, function(err, fields, files) {

        res.writeHead(200, {'content-type': 'text/plain'});


        var resultObj = {

            result : 'ok',

            size : files.thumbnail.size,

            path : files.thumbnail.path,

            name : files.thumbnail.name,

            type : files.thumbnail.type

        }


        res.end( JSON.stringify(resultObj));

        //res.end('File uploaded!');


        console.log(files.thumbnail.path + "Upload completed" );


        //console.log(util.inspect(files));


        //console.log(files.thumbnail.name);



    });


}



And

how to arduino wifi-shield firmware upgrade (for macOS 10.9)

|

1. 맥포트가 설치되어있다고 가정하고 dfu-programmer 를 설치 합니다.


sudo port install dfu-programmer

sudo port selfupdate

sudo port upgrade outdated



2. 사진처럼 와이파이쉴드만 따로 떼어내서 쉴드에 달린 마이크로 USB포트에 usb 캐이블로 직접 피씨에합니다.


빨간색으로 동그라미된 부분이 3번점퍼입니다. 이것을 close 시켜주여야 펌웨어 업데이트 됩니다



아두이노 보드에 붙이지말고 따로 떼낸상태에서 업그래이드합니다.



제손입니다. 손톱이 좀 기네요^^;




2. 깃허브의 아두이노 프로잭트 소스를 다운로드 받습니다.

https://github.com/arduino/Arduino


받은소스의 압축을 푸시고  스크립트폴더로 들어갑니다.

cd [압축파일이름]/hardware/arduino/firmwares/wifishield/scripts


3. 루트권한으로스크립트를 실행시켜줍니다. 


아두이노 가 /Applications/Arduino.app 에 설치 되어있다고 가정하면 다음과 같이 터미널에 입력합니다.

sudo ./ArduinoWifiShield_upgrade.sh  -a /Applications/Arduino.app/Contents/Resources/Java -f all








참고 :

http://arduino.cc/en/Hacking/WiFiShieldFirmwareUpgrading

http://forum.arduino.cc/index.php/topic,130124.0.html

http://arduino.cc/en/Hacking/DFUProgramming8U2

And

querySelector 팁 몇가지

|

1. 체크박스나 레디오버튼 선택 항목 얻어내기


item 로 묶었을 경우


input[name=item]:checked


2. document 뿐만 아니라 특정 노드에서도 함수 사용이 가능합니다. 그러므로 좀더 빠른 탐색을 위해서는 document 보다는 근접한 부모노드에서 쿼리 함수를 실행하는 것이 더 좋습니다. document 는 트리의 root 입니다.



And

우분투에 오라클 클라이언트 인터페이스 설치하기(OCI)

|


아래 싸이트에서 basic, sdk 를 다운받는다.


http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html



11.2 버전의 경우는 이름이 다음과 같다.



instantclient-basic-linux.x64-11.2.0.4.0.zip

instantclient-sdk-linux.x64-11.2.0.4.0.zip


unzip 을 이용해서 basic 을 압축풀고 그안에 들어가서 sdk 압축을 푼다.





sudo nano /etc/enviroment(또는 bash.bashrc) 를 열고 맨 밑으로 커서를 이동한다음 아래를 추가 합니다.


(압축을 푼 디랙토리가 /home/gbox3d/work/oracle/instantclient_11_2 라고 가정합니다.)


export OCI_HOME=/home/gbox3d/work/oracle/instantclient_11_2

export OCI_LIB_DIR=$OCI_HOME

export OCI_INCLUDE_DIR=$OCI_HOME/sdk/include

#export OCI_VERSION=12 # Optional. Default is 11.

export NLS_LANG=AMERICAN_AMERICA.UTF8


환경 변수를 시스템에 적용 시켜줍니다.(재부팅하고나면 리셋되므로 다시 해줘야합니다.)

source /etc/enviroment



심볼릭링크를 재정의 해줍니다. 12 버전은  뒷부분이 12.xxx가 됩니다. 그때그때 파일 이름을 보고 바꿔주시면됩니다.

cd $OCI_LIB_DIR
ln -s libclntsh.so.11.1 libclntsh.so
ln -s libocci.so.11.1 libocci.so


추가 라이브러리를 설치합니다.

sudo apt-get install libaio1


동적 라이브러리 캐쉬를 생성합니다.

 echo '/home/gbox3d/work/oracle/instantclient_11_2' | sudo tee -a /etc/ld.so.conf.d/oracle_instant_client.conf

 sudo ldconfig


재부팅해서 설정을 적용시킵니다.

sudo reboot


(주의 : 재부팅후에는 oci 를 사용하려면  source /etc/enviroment 를 다시 해주어야합니다.)


참고 : 맥용 oci 설치하기>>>>


출처 :

https://github.com/joeferner/node-oracle/blob/master/INSTALL.md





'server' 카테고리의 다른 글

node.js file uploader (파일 업로더 만들기)  (0) 2014.04.30
And
prev | 1 | 2 | 3 | 4 | 5 | 6 | 7 | ··· | 11 | next