Serial Communication with Arduino using Java

Hi,
I want to send String using Serial Communication to Arduino using Java Language
I'm using RXTX Library and its sample code http://rxtx.qbang.org/wiki/index.php/Two_way_communcation_with_the_serial_port
on Arduino I uploaded Code to Write Incoming Character on LCD.

Heres My Code:

    public static void sendData()
    {
    	try {
			out1.write('H'); //(out1 = out)
			out1.flush();
			System.out.println("Done");
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

It dont gives any error but arduino wont write char on lcd.
I'm using Arduino UNO
I tried sending string using C# and it worked but how to send string using java? what i have to add/change in my code?

It dont gives any error but arduino wont write char on lcd.

What does the Arduino code look like?

#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

String inData = "";

void setup()
{
  Serial.begin(9600);
  lcd.begin(8,2);
  lcd.clear();
  lcd.blink();
}

void loop()
{
  if (Serial.available() > 0) 
  {
    int h = Serial.available();
    for (int i=0;i<h;i++)
    {
      inData += (char)Serial.read();
    }
    lcd.print(inData);
}

this code works fine when i'm sending string using C# but it dont works with java

You haven't shown the Java code which opens the serial port, so we have no way of knowing whether you're opening the correct serial port and with the correct parameters.

Does your sketch do what you expected when you send the serial input via the Arduino serial monitor? The sketch doesn't look at all robust and I would have thought that by just accumulating every received character in a String (which is never reset) and then printing the accumulated String to the LCD (without controlling where the cursor is) it would probably go wrong after the first few characters but ought to display at least something, if it's receiving anything.

I have already posted it.
I'm using RXTX sample code: at http://rxtx.qbang.org/wiki/index.php/Two_way_communcation_with_the_serial_port
I have just added

sendData();

In main()
and
I added

sendData()

Method
and I have changed baud rate and port name to "COM7"

PeterH:
Does your sketch do what you expected when you send the serial input via the Arduino serial monitor? The sketch doesn't look at all robust and I would have thought that by just accumulating every received character in a String (which is never reset) and then printing the accumulated String to the LCD (without controlling where the cursor is) it would probably go wrong after the first few characters but ought to display at least something, if it's receiving anything.

When i send data from serial monitor it works. it writes characters on lcd (it works is my C# application too but it dont works with java)

Gigi10012:
I have already posted it.

No you haven't. You've given us a link to a site where we can find the code you started from, but not your actual code. The code snippet you actually posted didn't include the code to open the port.

On the site you linked to, I see code like this:

serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

Since you don't say you changed this part, I guess you haven't. If you had posted your actual code, I wouldn't have had to guess.

Your Java application and your Arduino sketch need to use identical port settings. Here, the speeds don't match.

PeterH:

Gigi10012:
I have already posted it.

No you haven't. You've given us a link to a site where we can find the code you started from, but not your actual code. The code snippet you actually posted didn't include the code to open the port.

On the site you linked to, I see code like this:

serialPort.setSerialPortParams(57600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);

Since you don't say you changed this part, I guess you haven't. If you had posted your actual code, I wouldn't have had to guess.

Your Java application and your Arduino sketch need to use identical port settings. Here, the speeds don't match.

Read my post. I'm saying that i have changed baud rate, and i added new "sendData()" method and i have changed port name to "COM7"

Gigi10012:
I have just added

sendData();

In main()
and
I added

sendData()

Method
and I have changed baud rate and port name to "COM7"

Are you going to post your actual code, then?

PeterH:
Are you going to post your actual code, then?

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class JavaSerialCommunication
{
    public JavaSerialCommunication()
    {
        super();
    }
    public static OutputStream out1;
    public static SerialPort port1;
    void connect ( String portName ) throws Exception
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
            
            if ( commPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
                port1 = serialPort;
                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();
                out1 = out;
                (new Thread(new SerialReader(in))).start();
                (new Thread(new SerialWriter(out))).start();

            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }     
    }
    
    /** */
    public static class SerialReader implements Runnable 
    {
        InputStream in;
        
        public SerialReader ( InputStream in )
        {
            this.in = in;
        }
        
        public void run ()
        {
            byte[] buffer = new byte[1024];
            int len = -1;
            try
            {
                while ( ( len = this.in.read(buffer)) > -1 )
                {
                    System.out.print(new String(buffer,0,len));
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }            
        }
    }

    /** */
    public static class SerialWriter implements Runnable 
    {
        OutputStream out;
        
        public SerialWriter ( OutputStream out )
        {
            this.out = out;
        }
        
        public void run ()
        {
            try
            {                
                int c = 0;
                while ( ( c = System.in.read()) > -1 )
                {
                    this.out.write(c);
                }                
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }            
        }
    }
    
    public static void main ( String[] args )
    {
        try
        {
            (new JavaSerialCommunication()).connect("COM7");
            sendData();
        }
        catch ( Exception e )
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public static void sendData()
    {
    	try {
    		char h = 'h';
			out1.write();
			out1.flush();
			System.out.println("Done");
			port1.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}

That Java code is pretty ugly, but I can't see anything that would stop it working. I suggest you try putting a delay after the output so that (a) it doesn't slam the port closed the moment it's buffered the data for transmission, and (b) it hangs around for long enough for you to receive and print anything that is received back over the serial port. Also, modify the sketch to print out some recognisable string at startup and also print something when it receives something over the serial port, so you can see whether you have forward and reverse comms. (Probably you haven't, but this would prove that and get us a step closer to finding out where the problem is.)

Oh, and put a delay after you have opened the port before you write to it. The Arduino would normally reset when you open the port, and you need to wait long enough for the boot loader to time out and the sketch to finish initialisation before it is ready to receive anything on the serial port.

I have JRuby code that communicates with Arduinos using Rxtx. Life is too short to use Java. I will happily share it if it's any use.

...R

Robin2:
Life is too short to use Java.

Java is perfectly usable, but the Java posted was pretty poor. In any case I suspect the problem is not related to the Java language, but just the way the Java program opens the port, immediately writes a single character and then closes the port. Whatever language you implement it in, that isn't going to work.