Created
July 16, 2013 15:36
-
-
Save ladislas/6009827 to your computer and use it in GitHub Desktop.
send serial command to arduino using node 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 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