Skip to content

Instantly share code, notes, and snippets.

@ladislas
Created July 16, 2013 15:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ladislas/6009827 to your computer and use it in GitHub Desktop.
Save ladislas/6009827 to your computer and use it in GitHub Desktop.
send serial command to arduino using node js
var serialport = require("serialport"),
SerialPort = serialport.SerialPort,
myPort;
var Fiber = require('fibers');
// Delay function using fibers
function sleep(ms) {
var fiber = Fiber.current;
setTimeout(function() {
fiber.run();
}, ms);
Fiber.yield();
}
var dataHeader = 0x0f,
dataFooter = 0xf0,
i = 0;
// Auto connect to the right serial port
serialport.list(function (err, ports) {
ports.forEach(function(port) {
if(port.manufacturer.indexOf("duino") != -1){
myPort = new SerialPort(port.comName,{
baudrate: 115200,
parser: serialport.parsers.readline(";")
});
console.log("Port found: " + port.comName);
}
});
});
Fiber(function() {
while(true){
console.log("i = " + i);
sleep(500);
i++;
//Start rolling
if(i == 20){
console.log("Sending data");
myPort.write(Buffer([dataHeader]));
myPort.write(Buffer([0x02]));
myPort.write(Buffer([0x01]));
myPort.write(Buffer([0x02]));
myPort.write(Buffer([0X96]));
myPort.write(Buffer([0x01]));
myPort.write(Buffer([0x02]));
myPort.write(Buffer([0x02]));
myPort.write(Buffer([0X96]));
myPort.write(Buffer([0x01]));
sleep(4000);
}
//Stop rolling
if(i == 30){
console.log("Sending data");
myPort.write(Buffer([dataHeader]));
myPort.write(Buffer([0x02]));
myPort.write(Buffer([0x01]));
myPort.write(Buffer([0x02]));
myPort.write(Buffer([0X00]));
myPort.write(Buffer([0x01]));
myPort.write(Buffer([0x02]));
myPort.write(Buffer([0x02]));
myPort.write(Buffer([0X00]));
myPort.write(Buffer([0x01]));
sleep(4000);
}
}
}).run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment