I solved it. This code below is for sending and receiving data to my Arduino.
public class IOData extends Observable implements SerialPortEventListener {
public SerialPort serialPort;
public String received = "tom";
/** The port we're normally going to use. */
private static final String portName = "/dev/tty.usbmodem1421"; //Change to whatever port your arduino is connected to.
public static BufferedReader input;
public static OutputStream output;
/** Milliseconds to block while waiting for port open */
public static final int TIME_OUT = 2000;
/** Default bits per second for COM port. */
public static final int DATA_RATE = 9600;
//Prepare for receiving/sending
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
// First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
if (currPortId.getName().equals(portName)) {
portId = currPortId;
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
// open serial port, and use class name for the appName.
serialPort = (SerialPort) portId.open(this.getClass().getName(), TIME_OUT);
// set port parameters
serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
char ch = 1;
output.write(ch);
// add event listeners
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
//This is called when receiving data from an Arduino.
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
String temp = "empty";
try {
temp = input.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Received this: " + temp);
received = temp;
// setChanged();
// notifyObservers();
}
}
//This simply sends the data
public static synchronized void writeData(String data) {
System.out.println("Sent: " + data);
try {
output.write(data.getBytes());
} catch (Exception e) {
System.out.println("could not write to port");
}
}
This is example code you can run on your Arduino (very simple code) does't do much, but you can build on it.
int led = 13;
void setup(){
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop(){
delay(100);
}
void serialEvent() {
int inc = 0;
while (Serial.available()){
inc = Serial.parseInt();
}
Serial.print("Works");
Serial.print(inc);
}
Hope it helped if someone has the some problem.