javaarduinoarduino-unojssc

Sending variable to Arduino COM port on ubuntu using Java


I need to send variable to Arduino UNO via COM port on Linux Ubuntu using Java programming language. With libraries JSSC or RXTX. Like:

String text = "turn_on";
write(text);

and like:

int num = 1;
write(num);

My Arduino code is like this:

include <SoftwareSerial.h>

void setup() {
  pinMode(9, OUTPUT);
  Serial.begin(57600);
}
int st;
void loop() {
  st = Serial.read();
  if(st == 1){
    digitalWrite(9, 1);
  }

}

I tried this code:

import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;

public class Test {

    private static SerialPort serialPort;

    public static void main(String[] args) {

        serialPort = new SerialPort("/dev/ttyUSB2");
        try {

            serialPort.openPort();

            serialPort.setParams(SerialPort.BAUDRATE_57600,
                                 SerialPort.DATABITS_8,
                                 SerialPort.STOPBITS_1,
                                 SerialPort.PARITY_NONE);

            serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN | 
                                          SerialPort.FLOWCONTROL_RTSCTS_OUT);

            serialPort.addEventListener(new PortReader(), SerialPort.MASK_RXCHAR);

            serialPort.writeInt(1);
        }
        catch (SerialPortException ex) {
            System.out.println(ex);
        }
    }

    private static class PortReader implements SerialPortEventListener {

        public void serialEvent(SerialPortEvent event) {
            if(event.isRXCHAR() && event.getEventValue() > 0){
                try {

                    String data = serialPort.readString(event.getEventValue());

                    serialPort.write(1);
                }
                catch (SerialPortException ex) {
                    System.out.println(ex);
                }
            }
        }
    }
}

How to do it?


Solution

  • Try sleeping after writing to serial port. Configure Arduino for flow control, First see if normal read and write are working then move to eventListener approach means if java write to arduino, arduino is able to read then send data from arduino and java side should be able to read. This will eliminate many possibilities. Further try some other libraries in parallel also like SerialPundit or fazecast on github.