LoginSignup
58
56

More than 5 years have passed since last update.

ofSerial を使用して シリアル通信で openFrameworks と Arduino を連携させる 方法について書きます。

下記書籍を参考にしました。

#上記の本は、厳しいレビューがついていますし、本は薄く、オシャレ感もありませんが、そもそも 国内に2種類しかでてない oF 専門書のうちのひとつですし、 Arduino, Wiiリモコン, Kinect などとのデバイスとの連携方法も載ってて、参考になる部分もあるので、意外とオススメです。

Arduino側

回路を組む

タクトスイッチの片方をGNDへ、もう片方をデジタルピンの2番に挿しています。

コード

Arduinoのコードはこんな感じです。

const int SW  = 2;

void setup(){

  // シリアル通信開始
  Serial.begin(9600);

  // ピンモード
  pinMode(SW,  INPUT_PULLUP);
}

void loop(){

  // スイッチの値を読み取る
  int value = digitalRead(2);

  if (value != HIGH) {

    Serial.println(1);
  } 
}

タクトスイッチが押されている間、"1" をシリアル通信で送ります。

openFrameworks側の実装

メンバ変数を追加

int nBytesRead = 0;
ofSerial serial;
char bytesReadString[4];

セットアップ

void testApp::setup(){

    ofBackground(255,255,255);

    // シリアル通信開始
    serial.setup("/dev/tty.usbmodem1411",9600);
}

シリアル通信を開始する ofSerial::setup の第1引数にはポート名を指定する必要があるのですが、このポート名は、ArduinoのIDEから、

[Tools] -> [Serial Port]

で確認できます。Arduinoをつないでいるポート名にチェックマークが付いています。

通信データの読み込みと描画

void testApp::update(){

    nBytesRead = 0;
    int nRead = 0;
    char bytesRead[3];
    unsigned char bytesReturned[3];

    memset(bytesReturned, 0, 3);
    memset(bytesReadString, 0, 4);

    // シリアル通信で受け取ったデータを読み込む
    while ((nRead = serial.readBytes(bytesReturned, 3)) > 0) {

        nBytesRead = nRead;
    };

    if (nBytesRead > 0) {

        memcpy(bytesReadString, bytesReturned, 3);
        string x = bytesReadString;
    }
}

void testApp::draw(){

    // 送られてきた文字列を表示
    string msg;
    msg += ofToString(nBytesRead) + " [bytes]" + "\n";
    msg += "read: " + ofToString(bytesReadString);
    ofSetColor(0);
    ofDrawBitmapString(msg, 100, 100);
}

動かしてみる

  • モニタ用に Arduino の [Tools] -> [Serial Monitor] を立ち上げておく
  • Arduinoのスイッチを押すと、シリアル通信で送られてきた情報が表示される
58
56
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
58
56