Search code examples
node.jsftdi

How can I communicate from node js to ftdi? (without ftdi module)


I'm using nodejs to sequence some stuff which is then to be sent to a FTDI, but I am unable to figure out how to do so.

I tried installing ftdi from npm, but its install script failed, so now I'd like to know how to do without it (teach one to fish). I'm not interested in getting that specific package to work, but I'd really like to know how it works instead.

So far my logic is this:

  1. I have installed a driver for ftdi. My beleif is that when I connect it to my computer, it and my computer come up with an agreement on how to communicate. What this agreement is, I'd like to know. Perhaps parameters on how to send/receive?

  2. I have installed a means of connecting to usb from node js, in this case I'm using npm usb. Perhaps there's a more direct route? I saw serialport in my searches.

  3. I should be able to find my ftdi using node usb. I've tried using usb.getDeviceList(), and have found no way to discern what is what from the list.

  4. Once I've selected the device, I should be able to send data to it (with my computer handling logistics of how that happens) .

Does all of this seem correct? Alternatively, would anyone be willing to show me a small example of finding an ftdi device and sending it serial data (assuming the drivers are installed)?


Solution

  • Found an answer on this site: https://itp.nyu.edu/physcomp/labs/labs-serial-communication/lab-serial-communication-with-node-js/

    1. install driver from ftdi. They'll have the most recent instructions for your os.

    2. install npm i serialport

    (I'm using typescript, so convert this to js if needed)

    Then, list all the ports. Try listing with your ftdi plugged in, and unplugged. You should see one extra entry. If not... sorry. Mine was called "/dev/tty.usbserial-A5XK3RJT"

    import SerialPort from 'serialport';
    
    // list serial ports:
    SerialPort.list(function (err, ports) {
      ports.forEach(function(port) {
        console.log("PORT", port.comName);
      });
    });
    

    Once you have your serial port name, just send a buffer of Uint8Array to it. For example:

    import SerialPort from 'serialport';
    
    // baudRate is specific to my project 
    const myPort = new SerialPort("/dev/tty.usbserial-A5XK3RJT", { baudRate: 57600 });
    ​var bellOnMidi = new Uint8Array(3);
    bellOnMidi[0] = (0b1001 << 4) + 2;
    bellOnMidi[1] = 1;
    bellOnMidi[2] = 0;
    myPort.write(Buffer.from(bellOnMidi));
    
    ​var bellOffMidi = new Uint8Array(3);
    bellOffMidi[0] = (0b1000 << 4) + 2;
    bellOffMidi[1] = 1;
    bellOffMidi[2] = 0;
    setTimeout(() => myPort.write(Buffer.from(bellOffMidi)), 500);
    

    I'm still uncertain on what goes on with usb drivers, but that's probably for another Q & A.