1
+ // IMPORTANT: install dependency via 'npm i node-hid' in the same location as the script
2
+ // If the install fails on windows you may need to run 'npm i -g windows-build-tools' first to be able to compile native code needed for this library
3
+
4
+ var HID = require ( 'node-hid' ) ;
5
+ var os = require ( 'os' )
6
+
7
+ var isWin = ( os . platform ( ) === 'win32' ) ;
8
+ var devices = HID . devices ( ) ;
9
+
10
+ // choose either of the following supported devices:
11
+ // Metro_nRF52840, Feather_nRF52840
12
+
13
+ var deviceInfo = devices . find ( Feather_nRF52840 ) ;
14
+ var reportLen = 64 ;
15
+
16
+ var message = "Hello World!"
17
+
18
+ // Turn our string into an array of integers e.g. 'ascii codes', though charCodeAt spits out UTF-16
19
+ // This means if you have characters in your string that are not Latin-1 you will have to add additional logic for character codes above 255
20
+ var messageBuffer = Array . from ( message , function ( c ) { return c . charCodeAt ( 0 ) } ) ;
21
+
22
+ // Windows wants you to prepend a 0 to whatever you send
23
+ if ( isWin ) {
24
+ messageBuffer . unshift ( 0 )
25
+ }
26
+
27
+ // Some OSes expect that you always send a buffer that equals your report length
28
+ // So lets fill up the rest of the buffer with zeros
29
+ var paddingBuf = Array ( reportLen - messageBuffer . length ) ;
30
+ paddingBuf . fill ( 0 )
31
+ messageBuffer = messageBuffer . concat ( paddingBuf )
32
+
33
+ // check if we actually found a device and if so send our messageBuffer to it
34
+ if ( deviceInfo ) {
35
+ console . log ( deviceInfo )
36
+ var device = new HID . HID ( deviceInfo . path ) ;
37
+
38
+ // register an event listener for data coming from the device
39
+ device . on ( "data" , function ( data ) {
40
+ // Print what we get from the device
41
+ console . log ( data . toString ( 'ascii' ) ) ;
42
+ } ) ;
43
+
44
+ // the same for any error that occur
45
+ device . on ( "error" , function ( err ) { console . log ( err ) } ) ;
46
+
47
+ // send our message to the device every 500ms
48
+ setInterval ( function ( ) {
49
+ device . write ( messageBuffer ) ;
50
+ } , 500 )
51
+ }
52
+
53
+
54
+
55
+
56
+ function Feather_nRF52840 ( d ) {
57
+ return isDevice ( 0X239A , 0X8029 , d )
58
+ }
59
+
60
+ function Metro_nRF52840 ( d ) {
61
+ return isDevice ( 0X239A , 0X803F , d )
62
+ }
63
+
64
+
65
+ function isDevice ( vid , pid , d ) {
66
+ return d . vendorId == vid && d . productId == pid ;
67
+ }
0 commit comments