반응형

이전 포스팅: https://gusdnr69.tistory.com/category/IOT%EA%B0%9C%EB%B0%9C/node.js

 

'IOT개발/node.js' 카테고리의 글 목록

코딩, 개발, 애니덕질

gusdnr69.tistory.com

 

play-sound는  mp3 파일에 한해서 재생이 됩니다.

다양한 음원 파일을 재생할 수 있는 라이브러리를 소개하겠습니다.

 

https://dyclassroom.com/reference-javascript/work-with-audio-in-javascript-using-howler-js

 

Work with audio in JavaScript using Howler.js - Reference JavaScript - DYclassroom | Have fun learning :-)

In this tutorial we will learn about Howler.js which makes working with audio in JavaScript easy and reliable across all platforms. Click here to visit Howler.js GitHub repository. Install If you have Node and NPM installed then use the following command i

dyclassroom.com

 

Howler.js 입니다. 웹 UI를 통해서 mp3외에 다른 형식의 음원파일도 재생이 가능합니다.

 

 

 

 

저는 wav파일을 재생하기 위해서 

node-aplay 

를 사용하였습니다.

 

 

설치 절차

sudo apt-get update
sudo apt-get upgrade
sudo rpi-update
sudo apt-get install alsa-base alsa-utils
sudo npm install node-aplay

 

 

 

예시 코드

var Sound = require('node-aplay');
 
// fire and forget:
new Sound('/path/to/the/file/filename.wav').play();
 
// with ability to pause/resume:
var music = new Sound('/path/to/the/file/filename.wav');
music.play();
 
setTimeout(function () {
    music.pause(); // pause the music after five seconds
}, 5000);
 
setTimeout(function () {
    music.resume(); // and resume it two seconds after pausing
}, 7000);
 
// you can also listen for various callbacks:
music.on('complete' function () {
    console.log('Done with playback!');
});

 

 

 pause나 resume은 미리 변수에 sound 객체를 저장해놓아야만 가능합니다. 

setTimeout 없이 사용하셔도 무방합니다.

 

 

반응형
반응형

play-sound 라는 npm을 사용해서 라즈베리파이에서 node.js를 통해서 음악을 틀 수 있습니다.

 

 

sudo npm install play-sound

 

해당 모듈을 설치하시고!

 

 

예시코드입니다. 

var player = require('play-sound')(opts = {})
 
// $ mplayer foo.mp3 
player.play('foo.mp3', function(err){
  if (err) throw err
})
 
// { timeout: 300 } will be passed to child process
player.play('foo.mp3', { timeout: 300 }, function(err){
  if (err) throw err
})
 
// configure arguments for executable if any
player.play('foo.mp3', { afplay: ['-v', 1 ] /* lower volume for afplay on OSX */ }, function(err){
  if (err) throw err
})
 
// access the node child_process in case you need to kill it on demand
var audio = player.play('foo.mp3', function(err){
  if (err && !err.killed) throw err
})
audio.kill()

 

이런 방식으로 사용해주시면 됩니다. foo.mp3대신 파일경로와 원하는 mp3파일을 넣어주시면 됩니다.

쓰레드 단위로 돌아가기 때문에 노래가 중복해서 틀어질 수 있습니다. 

적절한 예외처리를 해주셔야 할 것이고 

 

음악을 끄는 코드는 제일 아래에 코드인 

audio.kill()

입니다.

 

 

반응형
반응형

기존에 maria db를 설치하셔야 합니다. 

sudo apt-get update
sudo apt-get install mariadb-server

위 명령어로 설치합니다.

 

sudo mysql
use mysql;

mysql로 접속하고 사용하는 데이터베이스를 mysql로 선택해줍니다. (mysql 데베에 권한이 들어갑니다.)

 

 

 

select user, host, password from user;

이 명령어로 현재 계정상태를 확인할 수 있습니다.

quit;

로 디비에서 나가고

 

 

 

sudo nano /etc/mysql/mariadb.conf.d/50-server.cnf

50-server.cnf 파일에서 bind-address = 127.0.0.1부분을 주석처리합니다.

마리아디비 버전에 따라 다른지 모르겠는데, bind-address가 

sudo vi /etc/mysql/my.cnf 

이 위치에 있는 것들도 있으니 2경로 모두 확인해보시고  bind-address부분은 주석처리 하면 됩니다! (#)

 

이후 다시 

sudo mysql
use mysql;
grant all privileges on *.* to 'root'@'%' identified by 'root_passwd';
flush privileges;
select host, user, password from user;

 

root_passwd 부분은 원하는 비밀번호로 바꾸어야 합니다.

추가된 계정을 확인하시고 

quit로 나가시면 됩니다.

 

 

 

 

접속하고 싶으신 PC의 workbench에서 

 

hostname: 아이피

port: 3306

username:  지정하신 user이름

비밀번호: 지정하신 비밀번호

입력하고 들어가시면 됩니다.

이렇게 입력하시면 같은 네트워크내에서 가능합니다.

 

 

 

외부 ip에서 접속을 원할때는 포트포워딩이 필요합니다. 

 

 

 

 

 

 

 

반응형

'IOT개발' 카테고리의 다른 글

라즈베리파이 mysql 오류  (0) 2020.04.21
라즈베리파이 고정ip 할당하기  (0) 2020.04.14
라즈베리파이 원격제어하기  (0) 2020.04.11
반응형
pi@optimuspi:~ $ sudo apt-get install mysql-server
sudo: unable to resolve host optimuspi: Name or service not known
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Package mysql-server is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
However the following packages replace it:
  mariadb-server-10.0

E: Package 'mysql-server' has no installation candidate

 

해당 에러가 뜨는 이유입니다.

 

해석해보면 해당 버전에서는 더이상 mysql을 지원하지 않기 때문에 mariadb를 사용하라는 의미입니다.

 

https://qastack.kr/software/120178/whats-the-difference-between-mariadb-and-mysql

 

MariaDB와 MySQL의 차이점은 무엇입니까?

 

qastack.kr

 

mariadb를 사용하셔도 사용하는데 전혀 무방합니다. 

 

sudo apt-get install mariadb-server
mysql -v 

 

 

다음과 같은 화면을 보실 수 있습니다. 다음 포스팅에서는 mariadb를 사용하는 전반에 대해서 포스팅하겠습니다. 

반응형
반응형

주로 포트포워딩을 위해서 고정IP 할당을 합니다.

 

고정 IP 할당 아주 쉽습니다. 

 

루트디렉토리에서 

sudo vi /etc/network/interfaces

파일 제일 아래에 밑에 7줄을 추가해줍니다.

이때 address 값은 자신이 원하는 고정IP를 입력합니다. 

sudo reboot

 

하면 해당 고정ip가 할당이 됩니다. 

ifconfig 명령어를 통해서 확인할 수 있습니다. 

 

https://gusdnr69.tistory.com/77?category=763916

 

라즈베리파이 원격제어하기

1. Winscp FTP클라이언트를 사용해 사용하는 PC환경의 파일과 라즈베리파이의 파일을 서로 전달할 수 있게 만든 프로그램 아래 링크에서 다운이 가능합니다. http://winscp.net/eng/download.php 불러오는 중입니..

gusdnr69.tistory.com

 

다음 포스팅에는 포트포워딩을 통해서 다른 장소에서도 라즈베리파이에 접속해서 개발할 수 있는 방법을 포스팅하겠습니다. 

반응형
반응형

1. Winscp

FTP클라이언트를 사용해 사용하는 PC환경의 파일과 라즈베리파이의 파일을 서로 전달할 수 있게 만든 프로그램 

아래 링크에서 다운이 가능합니다.

http://winscp.net/eng/download.php

불러오는 중입니다...

(디폴트값) Host Name: IP값 User Name: ‘pi’ Password: ‘raspberry’ (ip는 ifconfig 명령어를 통해서 알 수 있습니다.)

 

 새로운 변화를 적용시킬땐 Reflush  라즈베리쪽으로 전송할땐 Upload  PC쪽 전송할땐 Down Load 입니다.

 

2. Putty 연결하기

 

라즈베리파이를 원격제어하는데 사용합니다. SSH 프로토콜 사용

 

위 처럼 IP를 입력하고 들어가면 됩니다. 

로그이름에 ‘pi’ 패스워드에 ‘raspberry’ 입력합니다. (디폴트) 

 

에러시

    Putty 연결 오류 설정에 SSH가 disable상태이면 연결X (라즈베리파이에 configration 옵션에서 ssh 상태를 변경해주면 됩니다.)

 

3. Tightvncserver 인스톨

 

vncserver는 라즈베리파이 GUI를 원격을 보며 작업할 수 있게 도와주는 프로그램입니다.

 

라즈베리파이측 

1) $ sudo apt – get update 명령 실행
2) $ sudo apt – get install tightvncserver 명령 실행

개발환경 측 

아래 링크에서 프로그램을 다운받습니다. 

https://www.tightvnc.com/download.php

 

Download TightVNC

Licensing Terms There are two licensing options available for TightVNC software: GNU General Public License version 2 (often abbreviated as GNU GPL). This is the default licensing option. It's completely free but it does not allow integration with closed-s

www.tightvnc.com

 

PC에서 TightVNC viewer를 실행 라즈베리의 IP값과 포트번호 5902 입력 (포트번호 고정)

 

반응형
반응형

 

node.js를 사용해서 LED와 같은 다양한 장치를 쉽게 제어할 수 있습니다.

 

node.js 개념이 궁금하시다면?

https://gusdnr69.tistory.com/32?category=763917

 

node.js 란? 🤷‍♂️

JavaScript 언어는 주로 어디에 사용될까요?? 웹프로그래밍에서 동적으로 움직이는 화면들에 사용됩니다. 그리고 새로고침이 되지 않았는데 동적으로 움직이는 텍스트들에도 사용됩니다. JavaScript도 하나의 프로..

gusdnr69.tistory.com

 

 

soketio를 사용하는 방법도 있지만, 기본적인 방법을 우선 설명드리겠습니다.

 

3색 LED와 같은 경우 2가지가 있습니다.  커먼 캐소드 방식과 커먼 애노드 방식입니다. 각각 긴 단자를 gnd나 5v에 연결하시면 됩니다.

 

커먼캐소드 코드입니다.

var http = require('http').createServer(handler); //require http server, and create server with function handler()
var fs = require('fs'); //require filesystem module
var io = require('socket.io')(http) //require socket.io module and pass the http object (server)
var Gpio = require('pigpio').Gpio, //include pigpio to interact with the GPIO
ledRed = new Gpio(4, {mode: Gpio.OUTPUT}), //use GPIO pin 4 as output for RED
ledGreen = new Gpio(17, {mode: Gpio.OUTPUT}), //use GPIO pin 17 as output for GREEN
ledBlue = new Gpio(27, {mode: Gpio.OUTPUT}), //use GPIO pin 27 as output for BLUE
redRGB = 0, //set starting value of RED variable to off (0 for common cathode)
greenRGB = 0, //set starting value of GREEN variable to off (0 for common cathode)
blueRGB = 0; //set starting value of BLUE variable to off (0 for common cathode)

//RESET RGB LED
ledRed.digitalWrite(0); // Turn RED LED off
ledGreen.digitalWrite(0); // Turn GREEN LED off
ledBlue.digitalWrite(0); // Turn BLUE LED off

http.listen(8080); //listen to port 8080

function handler (req, res) { //what to do on requests to port 8080
  fs.readFile(__dirname + '/public/rgb.html', function(err, data) { //read file rgb.html in public folder
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
      return res.end("404 Not Found");
    }
    res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
    res.write(data); //write data from rgb.html
    return res.end();
  });
}

io.sockets.on('connection', function (socket) {// Web Socket Connection
  socket.on('rgbLed', function(data) { //get light switch status from client
    console.log(data); //output data from WebSocket connection to console

    //for common cathode RGB LED 0 is fully off, and 255 is fully on
    redRGB=parseInt(data.red);
    greenRGB=parseInt(data.green);
    blueRGB=parseInt(data.blue);

    ledRed.pwmWrite(redRGB); //set RED LED to specified value
    ledGreen.pwmWrite(greenRGB); //set GREEN LED to specified value
    ledBlue.pwmWrite(blueRGB); //set BLUE LED to specified value
  });
});

process.on('SIGINT', function () { //on ctrl+c
  ledRed.digitalWrite(0); // Turn RED LED off
  ledGreen.digitalWrite(0); // Turn GREEN LED off
  ledBlue.digitalWrite(0); // Turn BLUE LED off
  process.exit(); //exit completely
});

 

커먼 애노드코드입니다.

var http = require('http').createServer(handler); //require http server, and create server with function handler()
var fs = require('fs'); //require filesystem module
var io = require('socket.io')(http) //require socket.io module and pass the http object (server)
var Gpio = require('pigpio').Gpio, //include pigpio to interact with the GPIO
ledRed = new Gpio(4, {mode: Gpio.OUTPUT}), //use GPIO pin 4 as output for RED
ledGreen = new Gpio(17, {mode: Gpio.OUTPUT}), //use GPIO pin 17 as output for GREEN
ledBlue = new Gpio(27, {mode: Gpio.OUTPUT}), //use GPIO pin 27 as output for BLUE
redRGB = 255, //set starting value of RED variable to off (255 for common anode)
greenRGB = 255, //set starting value of GREEN variable to off (255 for common anode)
blueRGB = 255; //set starting value of BLUE variable to off (255 for common anode)

//RESET RGB LED
ledRed.digitalWrite(1); // Turn RED LED off
ledGreen.digitalWrite(1); // Turn GREEN LED off
ledBlue.digitalWrite(1); // Turn BLUE LED off

http.listen(8080); //listen to port 8080

function handler (req, res) { //what to do on requests to port 8080
  fs.readFile(__dirname + '/public/rgb.html', function(err, data) { //read file rgb.html in public folder
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
      return res.end("404 Not Found");
    }
    res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
    res.write(data); //write data from rgb.html
    return res.end();
  });
}

io.sockets.on('connection', function (socket) {// Web Socket Connection
  socket.on('rgbLed', function(data) { //get light switch status from client
    console.log(data); //output data from WebSocket connection to console

    //for common anode RGB LED  255 is fully off, and 0 is fully on, so we have to change the value from the client
    redRGB=255-parseInt(data.red);
    greenRGB=255-parseInt(data.green);
    blueRGB=255-parseInt(data.blue);

    console.log("rbg: " + redRGB + ", " + greenRGB + ", " + blueRGB); //output converted to console

    ledRed.pwmWrite(redRGB); //set RED LED to specified value
    ledGreen.pwmWrite(greenRGB); //set GREEN LED to specified value
    ledBlue.pwmWrite(blueRGB); //set BLUE LED to specified value
  });
});

process.on('SIGINT', function () { //on ctrl+c
  ledRed.digitalWrite(1); // Turn RED LED off
  ledGreen.digitalWrite(1); // Turn GREEN LED off
  ledBlue.digitalWrite(1); // Turn BLUE LED off
  process.exit(); //exit completely
});

 

write함수의 사용법이 조금 다른 것이 특징입니다. 

 

아래 링크에 더욱 자세하게 설명되어있으니 참고하시면 좋을 것 같습니다. 

화이팅 :) 

 

참고자료:https://www.w3schools.com/nodejs/nodejs_raspberrypi_rgb_led_websocket.asp

 

Node.js Raspberry Pi RGB LED and WebSocket

Node.js Raspberry Pi RGB LED with WebSocket Using Pulse-Width Modulation In the previous chapters we have learned how to use WebSocket, and how to use GPIO to turn LEDs on and off. In this we will use chapter we use a RGB LED, with PWM (Pulse-width modulat

www.w3schools.com

 

반응형
반응형

JavaScript 언어는 주로 어디에 사용될까요??

웹프로그래밍에서 동적으로 움직이는 화면들에 사용됩니다. 그리고 새로고침이 되지 않았는데 동적으로 움직이는 텍스트들에도 사용됩니다.  JavaScript도 하나의 프로그래밍 언어이기에 프론트단에서 그러한 움직을 만들수 있는 것입니다. 

 

 

JavaScript를 크롬(Chrome)같은 브라우저에서만 쓰는 것이 아닌 브라우저 밖. 즉, 내 컴퓨터에서 다양한 용도로 확장하기 위해 만들어진 것이 바로 Node.js입니다. Node.js를 이용하면 Python과 같이 내 컴퓨터에서 File System를 이용할 수 있고, 서버를 만들 수도 있고 크롤링도 할 수 있습니다. JavaScript도 Python과 같은 프로그래밍 언어이기 때문입니다.

 

 

 

Node.js를 이용하여 Express같은 라이브러리를 이용해서 서버를 만들곤하지만, Node.js 자체는 웹서버가 아닙니다.  Node.js는 자바스크립트 런타임(JavaScript Runtime)으로 Node.js는 웹 서버를 만들 수 있는 하나의 방법에 불과합니다.

 

 

 

Node.js의 특징

1.비동기 I/O 처리: Node.js 라이브러리의 모든 API는 비동기식(async)입니다, 멈추지 않는다는거죠 (Non-blocking). Node.js 기반 서버는 API가 실행되었을때, 데이터를 반환할때까지 기다리지 않고 다음 API 를 실행합니다. 그리고 이전에 실행했던 API가 결과값을 반환할 시, Node.js의 이벤트 알림 메커니즘을 통해 결과값을 받아옵니다.

 

 

2. 빠른 속도: 구글 크롬(Google Chrome)의 V8 자바스크립트 엔진(JavaScript Engine)을 사용하여 빠른 코드 실행을 제공합니다.

 

 

3. 단일 쓰레드와 뛰어난 확장성: Node.js는 이벤트 루프와 함께 단일 쓰레드 모델을 사용합니다. 이벤트 메커니즘은 서버가 멈추지않고 반응하도록 해주어 서버의 확장성을 키워줍니다. 반면, 아파치(Apache)같은 일반적인 웹서버는 요청을 처리하기 위하여 제한된 쓰레드를 생성합니다. Node.js 는 쓰레드를 한개만 사용하고 아파치(Apache)같은 웹서버보다 훨씬 많은 요청을 처리할 수 있습니다.

 

Node.js를 쓰기 적합한 곳

다음과 같은 경우에 Node.js를 사용할 경우 좋은 효율성을 발휘할 수 있습니다.

  • 알림이나 실시간 대화같이 같이 데이터의 실시간 처리가 필요한 애플리케이션
  • 사용자의 입력과 출력이 잦은 애플리케이션
  • 데이터 스트리밍 애플리케이션
  • JSON API기반의 애플리케이션
  • 단일 페이지 기반의 애플리케이션

웹외에도, 장치를 조작하는데도 많이 사용됩니다. 

다음부터의 제 포스팅에서는 라즈베리파이에서의 node.js를 활용한 정보전달 및 장치제어에 초점을 두고 포스팅 하겠습니다.

반응형

+ Recent posts