PubNubに登録し、Publish KeyとSubscribe Keyを取得します。
②Arduinoのセットアップ
「ArduinoをJavaScriptで制御する」の手順でArduinoをセットアップします。
③PubNubモジュールのインストール
1.コマンドプロンプトを起動し、作業用フォルダに移動します。
2.「npm install pubnub」と入力します。
④コードの作成
1.次のJavaScriptコードを入力し、「main.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"; // // channel名の設定 | |
var five = require("johnny-five"); | |
var board = new five.Board({port: "COM3"}); | |
board.on("ready", function() { | |
var led = new five.Led(5); | |
// 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(); | |
} | |
} | |
}); | |
}); |
「var board = new five.Board({port: "COM3"});」の「COM3」は、Arduinoと通信を行うシリアルポートを指定します。
2.次のHTMLコードを入力し、「index.html」と名前を付けて保存します。
※「index.html」は、別のPC、インターネット上のWebサーバーなど、どこに置いても構いません。
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.コマンドププロンプトを起動し、作業用フォルダに移動します。
3.「node main.js」と入力します。
4.ブラウザで「index.html」を開き、[ON]ボタンのクリックでLED点灯、[OFF]ボタンのクリックでLEDが消灯することを確認します。
0 件のコメント:
コメントを投稿