Linux 串行端口数据通过/dev/ttyS0和文件读/写
我最近拿起了一根带有交叉适配器(空调制解调器)的串行电缆,并认为这可能是一个教育性的实验,看看我是否可以在两台Linux(Lubuntu)计算机之间通过它控制字节的传递和接收。我用Java编写了一些基本代码,将/dev/ttyS0“文件”作为输入和输出文件流打开 我能够用minicom、echo和cat来回发送数据。我假设这些程序的作者理解我所不理解的:)但由于某种原因,当我尝试对这段代码执行相同的操作时,传输端将挂起,直到添加了LF(ascii 10)字符。我认为操作系统一直在保存字节,直到它有某种理由发送一块数据。。。?另外,然后接收方报告了两份“10”收据的副本,我真的不明白 出于某种原因,我认为如果我写一个字节,一个应该立即显示在另一边,但事实并非如此 正如我所说的,这只是一个探索性的练习,除了更好地理解操作系统如何与串行端口交互之外,没有真正的结局。。。谢谢你提供的任何信息Linux 串行端口数据通过/dev/ttyS0和文件读/写,linux,serial-port,Linux,Serial Port,我最近拿起了一根带有交叉适配器(空调制解调器)的串行电缆,并认为这可能是一个教育性的实验,看看我是否可以在两台Linux(Lubuntu)计算机之间通过它控制字节的传递和接收。我用Java编写了一些基本代码,将/dev/ttyS0“文件”作为输入和输出文件流打开 我能够用minicom、echo和cat来回发送数据。我假设这些程序的作者理解我所不理解的:)但由于某种原因,当我尝试对这段代码执行相同的操作时,传输端将挂起,直到添加了LF(ascii 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());
}
}
}
对于您遇到的问题,您应该在两侧正确设置串行连接(hek2mgl所说的termios.h内容)。您不仅应将串行chardev作为文件打开,还应设置它 关于这一主题的好读物是:
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>
com.sparetimelabs
好问题!:)我曾经使用C
和termios.h
实现过这一点。我没有计划如何使用Java实现这一点。我只能说这是可能的,谢谢。这本书正是我需要更好理解的。我现在看到Linux默认设置为将串行端口作为终端,这不是我想要使用它们的目的。我不想在这里使用Java的API路线(如JavaComm或RxTx),所以我发现在两端使用“stty raw-F ttyS0”可以让它们完全按照我的想法运行,现在程序按预期运行。。。再次感谢!