2

我最近拿起了一根带有交叉适配器(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());
    } 
}
}
4

2 回答 2

2

对于您遇到的问题,您应在两侧正确设置串行连接(hek2mgl 正在谈论的 termios.h 内容)。您不仅应将串行 chardev 作为文件打开,还应进行设置。

关于这个主题的一个很好的阅读是:

关于Java和串口的一些东西:

于 2013-06-06T00:10:54.863 回答
0

PureJavaComm 与 JTermios 和 Maven,

在 Mac OS X、Linux 和 Windows 平台上,是 Sun 和 RXTX 项目的 JavaComm SerialPort 的开源、纯 Java 的直接替代品。

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>

参考:

于 2015-08-16T21:33:00.903 回答