gpt4 book ai didi

java - RXTX 双向串口通信第一次运行后不发送数据

转载 作者:行者123 更新时间:2023-11-29 09:15:04 26 4
gpt4 key购买 nike

我从 RXTX 网站编辑了一个已经制作好的示例。我也是 Java 和串行通信编程的新手。

该应用程序完美运行了一次。它从 PIC 读取缓冲区并发送我输入的数字。 LED 亮起,PIC 发回相同的缓冲区,询问一个数字。但是当我输入它时,LED 熄灭,没有任何东西再次亮起,我再次收到要求输入号码的消息。

微 Controller 的软件没有任何问题,因为它与 super 终端完美配合。

代码如下:

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();
}
}


}

最佳答案

你的问题(对我来说)并不清楚,因为不清楚你对图片进行的编程究竟是为了做什么。不过,我的猜测是,您对\n 字符作为终止符的期望是导致问题的原因。

关于java - RXTX 双向串口通信第一次运行后不发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10033160/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com