Last active
July 27, 2016 18:24
-
-
Save rstackhouse/502259e9d037a81e35a991f11c285ef3 to your computer and use it in GitHub Desktop.
Make a Lego Mindstorms EV3 brick beep over a USB connection with Node
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 LEGO_VENDOR_ID = 0x0694; | |
var EV3_PRODUCT_ID = 0x0005; | |
var DIRECT_COMMAND = 0x80; | |
var usb = require('usb'); | |
var device = usb.findByIds(LEGO_VENDOR_ID, EV3_PRODUCT_ID); | |
device.open(); | |
var interface = device.interface(0); | |
if (interface.isKernelDriverActive()) { | |
interface.detachKernelDriver(); | |
} | |
interface.claim(); | |
var buf = new Buffer(17); | |
buf.fill(0); // For debugging so if we use console.log(buf) we can see what bytes have been written. | |
// First two bytes is message length (excluding first two bytes) in Little Endian | |
buf.writeUInt16LE(15); | |
// Third and fourth bytes are the message counter in Little Endian | |
buf.writeUInt16LE(1, 2); | |
// Fifth byte is the command type | |
buf.writeUInt8(DIRECT_COMMAND, 4); | |
// Sixth and seventh bytes are local and global vars (which we aren't using here) | |
buf.writeUInt8(0x00, 5); | |
buf.writeUInt8(0x00, 6); | |
// Command follows starting with opSound (0x94) | |
buf.writeUInt8(0x94, 7); | |
buf.writeUInt8(0x01, 8); | |
buf.writeUInt8(0x81, 9); | |
buf.writeUInt8(0x02, 10); | |
buf.writeUInt8(0x82, 11); | |
buf.writeUInt8(0xe8, 12); | |
buf.writeUInt8(0x03, 13); | |
buf.writeUInt8(0x82, 14); | |
buf.writeUInt8(0xe8, 15); | |
buf.writeUInt8(0x03, 16); | |
console.log(buf); | |
var endpoints = interface.endpoints, | |
inEndpoint = endpoints[0], | |
outEndpoint = endpoints[1]; | |
// inEndpoint is in to PC | |
inEndpoint.transferType = usb.LIBUSB_TRANSFER_TYPE_BULK; | |
inEndpoint.startPoll(); | |
inEndpoint.on('data', function (data) { | |
console.log(data); | |
}); | |
inEndpoint.on('error', function (error) { | |
console.log(error); | |
}); | |
// outEndpoint is out to device | |
outEndpoint.transferType = usb.LIBUSB_TRANSFER_TYPE_BULK; | |
outEndpoint.transfer(buf, function (err) { | |
console.log(err); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment