①PubNubのアカウントの登録(無料)
PubNubに登録し、Publish KeyとSubscribe Keyを取得します。
②Raspberry Piのセットアップ
「Raspberry Pi 2のGPIOをJavaScriptで制御する」の手順でRaspberry Piをセットアップします。
③PubNubモジュールのインストール
1.ターミナルを起動し、作業用フォルダに移動します。
2.「npm install pubnub」と入力します。
④コードの作成
1.次のJavaScriptコードを入力し、「main-pi.js」と名前を付けて作業用のフォルダに保存します。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var publishKey = '<your Publish Key>'; | |
var subscribeKey = '<your Subscribe Key>'; | |
var channel = "led-onoff"; // チャンネル名 | |
var raspi = require('raspi-io'); | |
var five = require('johnny-five'); | |
var board = new five.Board({ | |
io: new raspi() | |
}); | |
board.on('ready', function(){ | |
var led = new five.Led('P1-7'); | |
// pubnub初期化 | |
var pubnub = require("pubnub")({ | |
ssl : true, | |
publish_key : publishKey, | |
subscribe_key : subscribeKey | |
}); | |
// channel購読(データ受信) | |
pubnub.subscribe({ | |
channel : channel, | |
callback : function(message){ | |
console.log('>', message); | |
if(message.action === 'on'){ | |
led.on(); | |
} else { | |
led.off(); | |
} | |
} | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE HTML> | |
<html lang="ja"> | |
<head> | |
<meta charset="UTF-8"> | |
<script src="https://cdn.pubnub.com/pubnub.min.js"></script> | |
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> | |
<script> | |
$(function(){ | |
var publishKey = '<your Publish Key>'; | |
var subscribeKey = '<your Subscribe Key>'; | |
var channel = "led-onoff" // channel名の設定 | |
// PubNub初期化 | |
var pubnub = PUBNUB.init({ | |
publish_key : publishKey, | |
subscribe_key : subscribeKey | |
}); | |
// データの送信 | |
function publish(action) { | |
var value = {'action': action}; | |
pubnub.publish({ | |
channel : channel, | |
message : value, | |
callback: function(message){ | |
console.log(message); | |
} | |
}); | |
} | |
// [ON]ボタンのクリックで文字列「on」を送信 | |
$('#on-button').click(function(){ | |
publish('on'); | |
}); | |
// [OFF]ボタンのクリックで文字列「off」を送信 | |
$('#off-button').click(function(){ | |
publish('off'); | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<button id="on-button">ON</button> | |
<button id="off-button">OFF</button> | |
</body> | |
</html> |
⑤動作の確認
1.ターミナルを起動し、作業用フォルダに移動します。
2.「sudo node main-pi.js」と入力します。
3.ブラウザで「index.html」を開き、[ON]ボタンのクリックでLED点灯、[OFF]ボタンのクリックでLEDが消灯することを確認します。
0 件のコメント:
コメントを投稿