jrxtxでシリアル通信

概要

Javaでシリアル通信。
jrxtxを使用します。
jrxtx(GitHub)

jrxtxはRXTXのラッパーです。
RXTX native libraryは必要となります。

Example

シリアルポートをmain関数のパラメータで受け取ります。
ボーレート等はSerialPortBuilderの各set〜メソッドで設定出来ます。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package jp.cloudsquare.java.testrxtx;
 
import java.io.DataInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
 
import org.openmuc.jrxtx.DataBits;
import org.openmuc.jrxtx.FlowControl;
import org.openmuc.jrxtx.Parity;
import org.openmuc.jrxtx.SerialPort;
import org.openmuc.jrxtx.SerialPortBuilder;
import org.openmuc.jrxtx.StopBits;
 
public class TestRXTX {
    /** シリアルポート */
    static SerialPort serialPort =  null;
 
    public static void main(String[] args) {
        try {
            boolean recvStart = false;
            List<Byte> recvData = new ArrayList<>();
            serialPort = SerialPortBuilder.newBuilder(args[0])
                                            .setBaudRate(115200)
                                            .setDataBits(DataBits.DATABITS_8)
                                            .setParity(Parity.NONE)
                                            .setStopBits(StopBits.STOPBITS_1)
                                            .setFlowControl(FlowControl.NONE)
                                            .build();
            InputStream inputStream = serialPort.getInputStream();
            DataInputStream dataInputStream = new DataInputStream(inputStream);
            while(true) {
                byte read = dataInputStream.readByte();
                // :
                // 受診後の処理
                // :
            }
        }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Java

Posted by shi-n