我編輯了RXTX網站上的一個已有的示例。我也是Java和串行通信編程的新手。RXTX雙向串行通信在第一次運行後不發送數據
該應用程序運行完美一次。它從PIC讀取緩衝區併發送我輸入的號碼。 LED燈和PIC發回相同的緩衝區,請求一個數字。但是當我進入它時,指示燈熄滅,沒有再亮起,我再次收到要求輸入數字的信息。
微控制器的軟件沒有問題,因爲它可以與超級終端完美配合。
的代碼如下:
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* This version of the TwoWaySerialComm example makes use of the
* SerialPortEventListener to avoid polling.
*
*/
public class Test
{
public Test()
{
super();
}
void connect (String portName) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned())
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if (commPort instanceof SerialPort)
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
OutputStream out = serialPort.getOutputStream();
serialPort.addEventListener(new SerialReader(in));
serialPort.notifyOnDataAvailable(true);
(new Thread(new SerialWriter(out))).start();
}
else
{
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
/**
* Handles the input coming from the serial port. A new line character
* is treated as the end of a block in this example.
*/
public static class SerialReader implements SerialPortEventListener
{
private InputStream in;
private byte[] buffer = new byte[1024];
public SerialReader (InputStream in)
{
this.in = in;
}
public void serialEvent(SerialPortEvent arg0) {
int data;
try
{
int len = 0;
while ((data = in.read()) > -1)
{
if (data == '\n') {
break;
}
buffer[len++] = (byte) data;
}
System.out.print(new String(buffer,0,len));
}
catch (IOException e)
{
e.printStackTrace();
System.exit(-1);
}
}
}
/** */
public static class SerialWriter implements Runnable
{
OutputStream out;
public SerialWriter (OutputStream out)
{
this.out = out;
}
public void run()
{
try
{
int c = 0;
while ((c = System.in.read()) > -1)
{
this.out.write(c);
}
}
catch (IOException e)
{
e.printStackTrace();
System.exit(-1);
}
}
}
public static void main (String[] args)
{
try
{
(new Test()).connect("COM3");
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我發現第二次運行時,Java應用程序向發送給PIC的字符串添加了一個新行。例如,不是'2',它會發送'[new line] 2' – 2012-04-05 18:01:15
您應該準確指定您正在使用的RXTX版本以及您正在運行的操作系統。有關於非阻塞接收事件的問題。例如:http://stackoverflow.com/questions/1391946/is-constant-polling-in-rxtx-necessary – kaliatech 2012-04-05 18:17:51
在閱讀你的第一條評論之後,我想到你可能沒有意識到'this.out.write (c);'除了輸入的字符外,還會發送確認鍵(\ n)。因此,取決於你的PIC是如何編碼的,也許這是搞亂了第二次「跑步」。 (通過「運行」,我認爲你的意思是第二個循環。) – kaliatech 2012-04-05 18:31:02