「ArduinoをJavaScriptで制御する」を参照してください。
②「socket.io」のインストール
1.コマンドププロンプトを起動し、作業用フォルダに移動します。
2.「npm install socket.io」と入力します。
③コードの作成
1.次のJavaScriptコードを入力し、「server.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 five = require("johnny-five"); | |
var board = new five.Board({port: "COM3"}); | |
board.on("ready", function() { | |
var html = require('fs').readFileSync('index.html'); | |
var http = require('http').createServer(function(req, res) { | |
res.writeHead(200, { | |
'Content-Type': 'text/html' | |
}); | |
res.end(html); | |
}); | |
var io = require('socket.io')(http); | |
http.listen(3000); | |
var led = new five.Led(5); | |
io.on('connection', function(socket) { | |
socket.on('msg', function(data) { | |
console.log(data); | |
data = data.replace(/^[\s ]+|[\s ]+$/g, ""); | |
if (data == "スイッチオン") { | |
led.on(); | |
} else if (data == "スイッチオフ") { | |
led.off(); | |
} else { | |
io.emit('msg', data); | |
} | |
}); | |
}); | |
}); |
2.次のHTMLコードを入力し、「index.html」と名前を付けて作業用のフォルダに保存します。
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"> | |
<title>音声制御テスト</title> | |
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script> | |
</head> | |
<body> | |
<script> | |
var socket = io(); | |
var recognition = new webkitSpeechRecognition(); | |
recognition.continuous = true; | |
recognition.lang="ja-JP" | |
recognition.onresult = function(event) { | |
var length = event.results.length; | |
if (length > 0) { | |
console.log(event.results[length-1][0].transcript); | |
socket.emit('msg', event.results[length-1][0].transcript); | |
} | |
} | |
</script> | |
<form> | |
<input type="button" value="音声入力開始" onclick="recognition.start()"/> | |
</form> | |
</body> | |
</html> |
④動作の確認
1.PCにマイクを接続します。
2.コマンドププロンプトを起動し、作業用フォルダに移動します。
3.「node server.js」と入力します。
4.Web Speech API対応のブラウザ(Chromeなど)で「http://localhost:3000」を開きます。
※ネットワーク上の他のPCやスマホからアクセスする場合は、「http://<IPアドレス>:3000」形式でURLを指定します。


6.「スイッチオン」と話すとLEDがオン、「スイッチオフ」と話すとLEDがオフすることを確認します。
※認識しない場合もあります。
Bluetoothデバイスのシリアルポートを指定すれば、無線通信も可能なので、スマホからの音声乳六でコントロールするロボットなども意外と簡単にできそうです。
0 件のコメント:
コメントを投稿