Raspberry Pi とArduinoをUSBケーブルで結びシリアル通信の実験をします。
RPi-arduino

1. Node-serialport 他のインストール
$ npm install serialport    
$ npm serialport --version
2.11.2
$ sudo apt-get install setserial
$ sudo setserial -g -G /dev/tty* 2>/dev/null 
/dev/ttyACM0 uart unknown port 0x0000 irq 0 baud_base 57600 spd_normal low_latency
/dev/ttyAMA0 uart undefined port 0x0000 irq 83 baud_base 187500 spd_normal
  1. serialportモジュールのインストール
  2. serialportモジュールのバージョン確認
  3.  バージジョン番号
  4. setserialユーティリティのインストール
  5. アクティブなシリアルポートを表示。
    /dev/ttyACM0 (arduino)
    /dev/ttyAMA0 (RPi シリアルコンソール用)
2. RPi <—[plain text]— Arduino

Arduinoからメッセージ(Hello world)をRPiへ送りRPiで表示する。

RPi(Node.js)側のスクリプト
var serialPort = require("serialport")
var sp = new serialPort.SerialPort("/dev/ttyACM0", {
  baudrate: 115200,
  parser:serialPort.parsers.readline("\n")
});

  sp.on('data', function(data) {
  console.log('data received: ' + data);
});
Arduino側のスケッチ
void setup(){
  Serial.begin(115200);
}

void loop(){
  Serial.println("Hello world");
  delay(1000);
}
実行結果
$ node serial.js 
data received: Hello world
data received: Hello world
data received: Hello world
data received: Hello world
3. RPi —[plain text]—> Arduino

RPiからメッセージ(Hello world)をArduinoへ送りLCDで表示する。

RPi(Node.js)側のスクリプト
var serialport = require("serialport");
var sp = new serialport.SerialPort("/dev/ttyACM0", {
  baudrate: 115200,
  dataBits:8,
  parity:'none',
  flowControl:false
});

sp.on("open", function () {
  console.log('open');
  setTimeout(function() {
    sp.write("Hello "); 
    sp.write("world\n");
    console.log('Sended msg'); 
  }, 2000); 
});

node-serialportのWebページに掲載されている例題プログラムはうまく動作しなかった。
ググるとシリアルポートをオープンするコマンドを出して,すぐにデータを送信してはダメなようだ。こちらのページ「node-serialportを使ってArduinoとシリアル通信@ヒートポンプ式」を参照して,シリアルポートをオープンした後setTimeout()で2000mS待つようにした。2000mSはカットアンドトライで決定した。私の環境では1800mS待つ必要があったので200mSの余裕を持たせて2000としている。

Arduino側のスケッチ
// include the library code:
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void recvStr(char *buf)
{
  int i = 0;
  char c;
  while (1) {
    if (Serial.available()) {
      c = Serial.read();
      buf[i] = c;
      if (c == '\n') break; 
      i++;
    }
  }
  buf[i] = '\0';  // \0: end of string
}

void setup() {
  // set up the LCD's number of columns and rows: 
  Serial.begin(115200);
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("RX started");
  lcd.setCursor(0, 1);
}

void loop() {
  char str[255]; // string buffer
  if (Serial.available()) {  // if recived serial signal
    recvStr(str);   // read serial data to string buffer
    lcd.print(str);
  }
}

\nが送られて来るまでストリングバッファに送られてきた文字をため,\nが来たらストリングバッファの文字列をLCDに表示する。

Follow me!