LoginSignup
8
7

More than 5 years have passed since last update.

processingでシリアル接続

Last updated at Posted at 2016-04-07

シリアル接続したデバイスをProcessingで制御したい場合があります。
今回RFIDとの通信テストをする必要があったのでちょっと調べてみました。


import processing.serial.*;

Serial port;

String data;

void setup () {

    size (800, 600);

    //接続可能なシリアルポートのリストを表示
    for (int i = 0; i < Serial.list ().length; i++) {
        println (Serial.list ()[i]);
    }

    //自分のPCに接続しているシリアルポートの番号と通信速度を設定
    //通信速度は接続するデバイスによって適宜変更
    port = new Serial (this, Serial.list ()[5], 38400);

    //RFIDのようなデバイスの場合は初期動作の設定コマンドなど
    //反応を返してもらうためのコマンドを送信
    //02007502020C038A0Dというコマンドをchar型に変換して
    //1バイトずつ送信(コマンド内容はデバイスよって異なる)
    port.write (char (0x02));
    port.write (char (0x00));
    port.write (char (0x75));
    port.write (char (0x02));
    port.write (char (0x02));
    port.write (char (0x0C));
    port.write (char (0x03));
    port.write (char (0x8A));
    port.write (char (0x0D));

}

void draw () {

}

//コマンドを送るとserialEventが発生してデバイスからの反応を受け取ることができる
//送られてくる内容はSerialオブジェクトpに1バイトで入っていて、全ての内容が送信される
//までserialEventが発生する
void serialEvent (Serial p) {

    //最初に送ったコマンドによってデバイスが応答するので
    //同じくchar型で1バイトずつ読み取る
    char in_byte = (char) p.read ();

    //改行を拾ったら次の動作
    if (in_byte == '\r') {
        println (data);
        data = "";
        //setupの時と同様に何らかのコマンドを送信
        port.write (char (0x02));
        port.write (char (0x00));
        port.write (char (0x75));
        port.write (char (0x02));
        port.write (char (0x02));
        port.write (char (0x0C));
        port.write (char (0x03));
        port.write (char (0x8A));
        port.write (char (0x0D));
    } else {
        //改行を拾うまで読み込んだchar型を16進数に変換して
        //変数dataに追加していく
        data += hex (in_byte, 2);
    }

}

8
7
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
8
7