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.