Search code examples
node.jsnode-serialport

NodeJS SerialPort Write Format


I am building a prototype automated testing tool for the company I work for that uses a SMAC Controller to move an item in front of a laser micrometer to be measured.

I am using the NodeJS SerialPort library to issue commands to the Controller (through RS232 Serial), but appear to be having some issues with the commands being run. The controller accepts commands in a format that is a combined hex and string (page 23-24 of this PDF explains more).

The command that I am trying to run is: 0x20 W 0x012C04 20. When I run this in PuTTY, it works perfectly but SerialPort seems to ignore it, I presume it's a formatting/datatype error but I am unsure how to correct this.

My code is:

const port = new SerialPort("COM1", {
    baudRate: 115200,
    dataBits: 8,
    stopBits: 1,
    parity: "none",
}, (err) => console.log(err))

if(!port.isOpen) port.open()

port.on('open', () => {
    console.log("Port opened successfully")
    port.write("0x20 W 0x012C04 20", (err) => {
        if(err) throw err;
        console.log("Write to port successful")
        port.close()
    })
})

Any help is greatly appreciated!


Solution

  • The solution was simple, all I was missing was the return at the end of the command being sent. I was able to operate the SMAC Controller with the following command:

    0x20 W 0x012C04 20\r

    The full code used is:

    const port = new SerialPort(SMAC, {
        baudRate: 115200,
        dataBits: 8,
        stopBits: 1,
        parity: "none",
    }, (err) => console.log(err))
    
    if(!port.isOpen) port.open()
    
    port.on('open', () => {
        console.log("Port opened successfully")
    
        const macro = "0x20 W 0x012C04 20\r"
    
        // Call Macro 20
        port.write(macro, (err) => {
            if(err) throw err;
            console.log("Write to port successful")
            port.close()
        })
    })