Created
May 15, 2016 17:05
-
-
Save ferryzhou/1ec4f0b1dddf152b66f316328d3fdf51 to your computer and use it in GitHub Desktop.
connect to mbot through bluetooth from nodejs
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
// Based on tutorial here: | |
// https://itp.nyu.edu/physcomp/labs/labs-serial-communication/lab-serial-communication-with-node-js/ | |
// Examples: | |
// node test.js /dev/tty.Makeblock-ELETSPP | |
var serialport = require('serialport'); | |
var SerialPort = serialport.SerialPort; | |
var portName = process.argv[2]; | |
// turn led green | |
// ff 55 09 00 02 08 07 02 00 ff 00 00 | |
var ledGreenCmd = new Buffer([0xff, 0x55, 0x09, 0x00, 0x02, 0x08, 0x07, 0x02, 0x00, 0xff, 0x00, 0x00]); | |
var ledOffCmd = new Buffer([0xff, 0x55, 0x09, 0x00, 0x02, 0x08, 0x07, 0x02, 0x00, 0x00, 0x00, 0x00]); | |
var myPort = new SerialPort(portName, { | |
baudRate: 115200, // baud rate for makeblock. | |
parser: serialport.parsers.readline("\n") | |
}); | |
myPort.on('open', showPortOpen); | |
myPort.on('data', showSerialData); | |
myPort.on('close', showPortClose); | |
myPort.on('error', showError); | |
function showPortOpen() { | |
console.log('port open. Data rate: ' + myPort.options.baudRate); | |
changeLedAndClose(); | |
} | |
function showSerialData(data) { | |
console.log(new Buffer(data)); | |
} | |
function showPortClose() { | |
console.log('port closed.'); | |
} | |
function showError(error) { | |
console.log('Serial port error: ' + error); | |
} | |
function changeLedAndClose() { | |
myPort.write(ledGreenCmd); | |
setTimeout(function() { | |
console.log('turn off light'); | |
myPort.write(ledOffCmd); | |
console.log('close port ....') | |
myPort.close(); | |
}, 3000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment