takluiper takluiper - 5 months ago 56
Java Question

Send String from Java to Arduino (simple example)


It is solved. I put a
Thread.sleep(4000);
after opening the port in the java code and now it works. The problem was that the arduino is reset everytime the port is opened. When i was sending the data, the arduino wasn't ready to listen.


I'm new to arduino and Java, but i made a program so simple that I don't get why isn't working.

I send a String to the serial port that correspond to arduino (COM5):

import java.io.*;
import java.util.*;
import gnu.io.*;

public class SimpleWrite {
static Enumeration portList;
static CommPortIdentifier portId;
static String messageString = "color FF00FFEND";
static SerialPort serialPort;
static OutputStream outputStream;

public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();


while (portList.hasMoreElements()) {

portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

if (portId.getName().equals("COM5")) {

try {
serialPort = (SerialPort)
portId.open("SimpleWriteApp", 2000);
} catch (PortInUseException e) {System.out.println("err");}
try {
outputStream = serialPort.getOutputStream();
} catch (IOException e) {System.out.println("err1");}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {System.out.println("err2");}
try {
outputStream.write(messageString.getBytes());
System.out.println(messageString);

outputStream.close();
serialPort.close();

} catch (IOException e) {System.out.println("err3");}
}
}
}
}
}


and the code in arduino to get that string:

char inputBuffer[10];

void setup() {
Serial.begin(9600);
}

void loop() {
while (true)
{
if (Serial.available() > 0) {
Serial.readBytes(inputBuffer, Serial.available());
delay(5000);
Serial.print("I got this ->");
Serial.print(inputBuffer);
Serial.println("<-");
}
}
}


the while(true) is for testing purposes. I dont get nothing printed, and I dont know where the problem is. I have seen all the post about arduino and java here and i dont find nothing that helps.
Thanks for the help and sorry if it is a stupid question, im a newbie to this

Im using RXTXcomm.jar. Version: RXTX-2.2-20081207

Answer

It is solved. I put a Thread.sleep(4000) after opening the port in the java code and now it works. The problem was that the Arduino is reset everytime the port is opened, so I was sending the data when the Arduino wasn't ready to listen.

char inputBuffer[10];   

void setup()
{                
    Serial.begin(9600);  
}

void loop()
{
     while (true) 
     {
          if (Serial.available() > 0)
          {
              Serial.readBytes(inputBuffer, 10);
              delay(5000);
              Serial.print("I got this ->");
              Serial.print(inputBuffer);
              Serial.println("<-");
          }
     }
}