简体   繁体   中英

Reading and writing to a serial port using shell and Java

I am trying to read and write to a serial port using a combination of shell and java. The goal is to be able to use a PrintWriter and a BufferedReader to send and receive commands from a device connected to a serial port. I know that this can be done in different ways (without using shell) but this is not what I am looking for. I want to be able to do this using shell and java.

Here is my code:

static String port = "/dev/tty.usbmodem411";
static int baudRate = 9600;
private static String command = "screen " + port + " " + baudRate;

public static void main(String[] args) throws Exception {
    System.out.println("Command is " + command);
    Process p = Runtime.getRuntime().exec(command);
    //p.waitFor();

    BufferedReader reader =
            new BufferedReader(new InputStreamReader(
            p.getInputStream()));
    String line = reader.readLine();
    while(true)
    {
        if (line != null) {
            System.out.println(line);

        }
        line = reader.readLine();
    }

}

With this code, I am specifically trying to read from the serial port. I am using java to run a shell command to access a serial port and then read the output from the command.

However, when I run this code I always get a message saying "Must be connected to a terminal." I have also tried changing the line command = "screen " + port + " " + baudRate; to command = "screen -dm" + port + " " + baudRate; , but then I get no output whatsoever. I have consulted several similar questions, Executing screen command from Java and How to open a command terminal in Linux? but I still can't figure out what I should do to fix this problem. I have a feeling that it must be something very simple, but after hours of research I can't figure out what to do.

Instead of screen you may use command cu from UUCP package. To install UUCP package sudo apt-get install uucp or sudo yum install uucp .

Then use this command: static String command = "cu -l " + port + " -s " + baudRate;

Some explanation:

Your description suggests that you simply need to access the stream received on the serial port. You indicate that you wish to use a shell command to access the port. Why not use cat ... to send the content received from the port to the standard output.

If this works, then why is it not possible to just open the serial port and read from it directly?

Using screen would seem to bring in all the full screen handling provided by this window manager that is unlikely to be handled correctly. For example, what terminal type should screen format the output for?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM