Java调用RXTX库与Arduino进行串口通讯需注意的编程问题

准备用Arduino做一个jtag来调试WRTNode,在使用RXTX库与Arduino通讯时,出现了一些问题,总结如下:

1.在设置串口参数和获取Serial的输入/输出之间,需要至少2s的延时,否则串口通讯将不正常,但程序却没有任何的提示!

   1: serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
   2: // 延时2s
   3: Thread.sleep(2000); 
   4: // open the streams 
   5: input = new BufferedReader(new InputStreamReader(serialPort.getInputStream())); 
   6: output = new BufferedWriter(new OutputStreamWriter(serialPort.getOutputStream()));

2.读取串口数据时,不能简单的这样调用

String line=input.readline();

这样输出的数据很有可能是空(因为数据是缓冲了的,很有可能还没有读到任何数据!)

需要这样写:

   1: String line = null; 
   2: while ((line = input.readLine()) != null) { 
   3:     System.out.println(line); 
   4: }

另:参考StackOverflow上的这篇文章

http://stackoverflow.com/questions/5219450/rxtx-serial-connection-blocking-read-problem

Use RXTX-2.2pre2, previous versions have had a bug which prevented blocking I/O from working correctly.

And do not forget to set port to blocking mode:

   1: serialPort.disableReceiveTimeout();
   2: serialPort.enableReceiveThreshold(1);

你可能感兴趣的:(RXTX,Arduino,串口,jtag,java)