3

I am trying to rink Raspberry Pi and Arduino by serial communication. My purpose is that the user controls a LED of Arduino from Raspberry Pi.

I found an example code of serial communication and it sends a String to Arduino automatically every 2sec. But I want to make two things:

  1. Change the value sent instead of 'hello'.
  2. And the user can send the value any time he wants, not automatically.

Can you help me please? I am not good on node.js.

var SerialPort = require("serialport")
var serialPort = new SerialPort('/dev/ttyACM0', 
{   baudrate: 9600,
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    flowControl: false
});

serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) { // 아두이노로부터 전달된 데이터
    console.log('data received: ' + data);
});

serialPort.write("Hello from Raspberry Pi\n", function(err, results) {
    console.log('err ' + err);
    console.log('results ' + results); //전송한 바이트 수
});

setInterval( 
function() { // 2초마다 아두이노에게 문자열을 전송하는 예
   serialPort.write('hello');
}, 2000);
});

1 Answer 1

1

This is not that far off from working. A few minor tweaks 1. 'baudrate' should be mixed-caps 'baudRate'. 2. For anyone running this code, you do, of course, need to find the device name (the first parameter to the Serial Port constructor, in the example above '/dev/ttyACM0'). One way to find this is to open the Arduino IDE and look at 'Tools' | 'Port' once you find the one that communicates with the Arduino. 3. Lastly, the code above confuses by writing in two places. Just write in the setInterval function. This sends the 'hello' string every 2 seconds.

Here is the code that worked for me:

var SerialPort = require("serialport")
var serialPort = new SerialPort('/dev/cu.usbmodem15',
{   
  baudRate: 9600,
  dataBits: 8,
  parity: 'none',
  stopBits: 1, 
  flowControl: false
});

serialPort.on("open", function () {
  console.log('comm open');
  serialPort.on('data', function(data) {
    console.log('data received: ' + data);
  });

  setInterval( 
    function() { 
      serialPort.write('hello');
    }, 2000
  );
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.