Search code examples
node.jsstringarduinoserial-portled

How to send data as a string from NodeJs runtime to Arduino board using Serial communication?


I am working in a project that requires serial communication between Arduino board and NodeJs runtime in Raspberry Pi.

I want to send a string like "255,100,100,255" from NodeJs program inside my Pi to Arduino board to control the brightness of 4 lights. 4 elements inside the string are the brightness of each light.

How to code in both NodeJs and Arduino program so that Arduino board receive all the string?


Solution

  • You can use the module serialport.

    First install it using

    npm i serialport

    Then in your NodeJS code you can create a sender:

    let serial = require("serialport").SerialPort;
    let sp = new serial("/dev/ttyACM0", { baudrate: 9600 });
    sp.on("open", function(){
        sp.write("255,100,100,255", function(err, res) {
            if (err) return console.log(err);
        });
    });
    

    While on your arduino you can make a receiver:

    int incomingByte = 0;
    void setup(){ Serial.begin(9600); }
    void loop(){
        if (Serial.available() > 0) {
            incomingByte = Serial.read();
            Serial.println(incomingByte);
        }
    }