Created
October 30, 2016 14:27
-
-
Save 7m4mon/cbc73a8feead7f7d47d60bf2a771a37a to your computer and use it in GitHub Desktop.
This file contains 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 express = require('express'); | |
var app = require('express')(); | |
var http = require('http').Server(app); | |
var port = process.env.port || 1337; | |
var io = require('socket.io')(http); | |
var SerialPort = require('serialport').SerialPort; | |
var serial = new SerialPort('COM1', { //SZはCOM3 | |
baudrate: 9600 | |
}); | |
var statusStr: string = "."; | |
var civCommandTmp = ""; | |
app.use(express.static(__dirname + '/public')); | |
app.get('/', function (req, res) { | |
res.sendfile('index.html'); | |
}); | |
http.listen(3000, function () { | |
console.log('listen 3000 port'); | |
}); | |
serial.on('open', function () { | |
console.log('open'); | |
}); | |
serial.on('data', function (data) { | |
//0.52秒に一度送られてくる超音波センサの値をcmになおして表示する。 | |
var distanceString = data.toString(); | |
var distanceNum = parseFloat(distanceString); | |
if (distanceNum == 65535 || distanceNum == 0) { //たまに超音波センサが固まって65535や0を返すときがある…マイコン側で対策。 | |
distanceString = "Distance: " + "--- cm"; | |
} else { | |
distanceNum = distanceNum * 0.187; //11サイクル、4MHz、音速340m/s | |
distanceString = "Distance: " + distanceNum.toFixed(0) + " cm"; | |
} | |
//動作確認用に受信したらドットを点滅させる。 | |
statusStr = (statusStr == ".") ? "" : "."; | |
distanceString += statusStr; | |
io.emit('distance', distanceString); | |
}); | |
//コマンドを受信したら、シリアルポートに書き込む | |
io.on('connection', function (socket) { | |
socket.on('sendcommand', function (msg) { | |
console.log(msg); | |
serial.write(msg, function (err, results) { | |
}); | |
io.emit('sendedcommand', msg); //他のブラウザとの同期のためにコマンドをemitする | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment