我最近选择了带有交叉适配器(Null Modem)的串行电缆,并认为它可以进行教育实验,看看我是否可以在两台Linux(Lubuntu)计算机之间进行一些受控的传递和字节接收。我在Java中编写了一些基本代码,它们打开/ dev / ttyS0“文件”作为输入和输出文件流。
我可以使用minicom以及echo和cat来回发送数据。我假设这些程序的作者理解我不知道:)但由于某种原因,当我尝试对此代码执行相同操作时,发送方会挂起,直到添加了LF(ascii 10)字符。我认为操作系统持有字节,直到它有某种理由发送一大块数据......?另外,然后接收方报告“10”收据的两份副本,我真的不明白。
出于某种原因,我想如果我写一个字节,就应该立即在另一边显示,但事实并非如此。
正如我所说,这只是一个探索性的练习,除了更好地理解操作系统如何与串口交互之外,没有真正的最终游戏......感谢任何信息!
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class SOtest {
public static void main(String[] args) {
SOtest sot = new SOtest();
sot.rx(); // or sot.tx() for the transmit side
}
public void tx() {
FileOutputStream nmoutfile;
try {
nmoutfile = new FileOutputStream("/dev/ttyS0");
nmoutfile.write(49); // ascii value 10 still needed...?
nmoutfile.close(); // doesn't force value 49 to send
} catch (Exception ex) {
System.out.println(ex.getMessage().toString());
}
}
public void rx() {
FileInputStream nminfile;
try {
nminfile = new FileInputStream("/dev/ttyS0");
while (true) {
System.out.println(nminfile.read());
}
} catch (Exception ex) {
System.out.println(ex.getMessage().toString());
}
}
}
答案 0 :(得分:1)
对于你遇到的问题,你应该正确设置双方的串行连接(heios2mgl正在谈论的termios.h)。您不仅要将序列化的chardev作为文件打开,还要将其设置。
关于这个问题的好读物是:
关于Java和串口的一些内容:
答案 1 :(得分:0)
开源,纯Java,替代Sun和RXTX项目的Java OSm SerialPort,适用于Mac OS X,Linux和Windows平台。
JTermiosReadDemo.java:
import java.io.IOException;
import java.util.Scanner;
import purejavacomm.CommPortIdentifier;
import purejavacomm.NoSuchPortException;
import purejavacomm.PortInUseException;
import purejavacomm.SerialPort;
import purejavacomm.UnsupportedCommOperationException;
public class JTermiosReadDemo {
public static void main(String[] args) throws IOException, PortInUseException, NoSuchPortException, UnsupportedCommOperationException {
String port = "/dev/ttyUSB0";
SerialPort serialPort = (SerialPort) CommPortIdentifier.getPortIdentifier(port).open(
JTermiosDemo.class.getName(), 0);
Scanner scanner = new Scanner(serialPort.getInputStream());
while (scanner.hasNext()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}
的pom.xml:
<dependencies>
<dependency>
<groupId>com.sparetimelabs</groupId>
<artifactId>purejavacomm</artifactId>
<version>0.0.22</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>com.sparetimelabs</id>
<url>http://www.sparetimelabs.com/maven2</url>
</repository>
</repositories>
参考: