我正在开发一个项目,通过RS485串行连接在两个Raspberry Pi之间发送数据。为此,我编写了一个Java程序来发送数据。 安装程序正在工作,但我无法改变我在Java编程中的数据传输速度。我使用了一个带有25kb随机数据和两个Raspberry Pi Model 1B的测试文件。作为一个库,我正在使用RXTX Java库。Java串行端口无法改变Raspberry Pi的速度
我已更改/boot/config.txt
和/boot/cmdline.txt
中的设置,以便我可以使用串行端口并更改速度。
为了测试硬件是否可以做到这一点,我用简单的控制台命令发送一些数据。一个Raspi发送:
cat 25kTestfile.txt > /dev/ttyAMA0
另一个接收:
cat /dev/ttyAMA0 > 25kTestfile.txt
我改变的速度与sudo stty
。 通过这个命令行设置,我可以发送高达1Mb的数据并改变我喜欢它的速度。
但是在我的Java程序中,速度并没有改变。无论将串行端口设置为115200还是1000000,发送速度都保持不变。用我的程序,发送25k需要3秒以下,控制台0.3秒。
Java程序由两个文件组成。我已经包含了下面程序中最重要的部分。一个文件来设置串口连接在这里。
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class SerialConnect {
private SerialPort serialPort = null;
private InputStream in = null;
private OutputStream out = null;
private CommPort commPort = null;
private CommPortIdentifier portIdentifier = null;
void connect(String portName) throws Exception {
portIdentifier = CommPortIdentifier
.getPortIdentifier(portName);
if(portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
int timeout = 2000;
commPort = portIdentifier.open(this.getClass().getName(), timeout);
if(commPort instanceof SerialPort) {
serialPort = (SerialPort)commPort;
serialPort.setSerialPortParams(1000000,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
in = serialPort.getInputStream();
out = serialPort.getOutputStream();
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
[...]
public void write(byte[] input) {
try {
for(int i = 0; i < input.length; i++) {
this.out.write(input[i]);
}
this.out.flush();
} catch(IOException e) {
e.printStackTrace();
}
}
public void write(byte input) {
try {
this.out.write(input);
} catch(IOException e) {
e.printStackTrace();
}
}
[...]
public SerialConnect() {}
public SerialConnect(String portName) {
try{
connect(portName);
}
catch (Exception e) {
System.out.println("Error Failed to connect port.\n");
}
}
}
它采用串行连接的其他在这里:现在
File outFile = new File("./25kTestfile.txt");
FileInputStream in = new FileInputStream(outFile);
byte[] c = new byte[(int)outFile.length()];
in.read(c);
SerialConnect serialConnection = new SerialConnect("/dev/ttyAMA0");
if(serialConnection == null) {
System.out.println("Could not open Serial port.\n");
return;
}
serialConnection.write(c);
我的问题是:为什么速度没有改变?我需要设置一些其他的东西吗? Java在Raspi上如此之慢以至于发送速度不可能更快?