Search code examples
javarxtx

java RXTX send string


i'm trying to use the RXTX java library to send strings by click listeners in my gui, but i can't edit the code of the RXTX to send strings , where it only responds to input from the console, so how can i edit the code to not only send data that is input from the console?

i'm using the same code here:

http://rxtx.qbang.org/wiki/index.php/Two_way_communcation_with_the_serial_port

I have tried writing this extra function and called it from other classes:

public void writetoport() {
    String serialMessage = "test";
    try {
        // i have made 'out' as a global variable// 
        this.out.write(serialMessage.getBytes());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

But I get this error in the console:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at TwoWaySerialComm.writetoport(TwoWaySerialComm.java:121)

Solution

  • in the twowaycommuncation class, you can do something like this in that if statement:

    if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(115200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();
    out1=out;  //add this line, where out1 is a global variable//  
                (new Thread(new SerialReader(in))).start();
             (new Thread(new SerialWriter(out))).start();
    
            }
    

    then from anywhere in this class you send a string like this:

      public void writetoport(String send) {
    
        try {
                out1.write(send.getBytes());
                out1.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
    

    or whatever way you want to do.

    so now you can send strings you have defined in you code or by inputting it in the console.