[Engineering] Arduino to Java Serial Communication 2

In this post, I will talk about using Java as a client and Arduino as a server. To keep it simple, we will only use the Arduino’s built-in LED 13. Before proceeding, please read my other post about Arduino to Java Communication through Serial Port if you haven’t already.

In summary, the only differences in the Java’s side is that we will use jSSC’s serial write method instead of serial read as follows:

serialPort.writeByte(data);

I did a bit more messing around with the Serial stuffs, combining with stuffs I learned from the Space Hopper project with Zorexx, I think I got a bit better at this. Hopefully I don’t screw anyone up by writing the wrong theory like that global variable stuffs that I used to do in High School, lol.

So, in serial communication, we are sending a series of bytes through the serial port. A unsigned byte only have a range from 0 to 255, where as a signed byte only have a range of -128 to 127. Therefore, we are very limited in the amount of data we can send through. That is why in the earlier post, I converted everything into a String, then individually to an array of chars and finally an array of bytes in order to keep everything simple and in order. Otherwise, if I try to send a value through that is larger than 255, then I have to somehow split it into several bytes and the math get complicated. Well, I guess it is do-able since the math will definitely not be as hard as rocket science math, but hey, who want to do unnecessary math?

Char to byte / byte to char is an easy conversion, since all it really does it looking up the matching value in the ASCII code table.

Back on topic, follows are the code I used for a simple Java client and Arduino server. All they really do is the past data from the client side to the server side. The client can control the Arduino’s LED by sending the appropriated values.

If you haven’t figure it out by now, all you really need to do for the hardware hook up is to hook up the Arduino to your computer through a USB cable, lol. Remember to close the Arduino Comm Monitor before running the Java part. You can only have one program using the serial connection at a time.

Arduino Server


/* Yu Hin Hau
 * Java to Arduino Communication (Server)
 * 5/18/2012
 */
char operation = 0;

void setup() {
 Serial.begin(9600);
 pinMode(13, OUTPUT);
}
void loop() {

 //Read from Serial if Data is Available
 if (Serial.available() > 0)
 {
 operation = Serial.read();
 }
/*Remember that the data we sent through
* from the client are byte casted char,
* therefore, the value that get sent
* through are ASCII numerical codes.
* All we need to do to use this data
* is to convert / compare it back with
* a char type value.
*/

//LED Off
 if(operation == '0')
 digitalWrite(13, LOW);

//LED On
 else if(operation == '1')
 digitalWrite(13, HIGH);

//LED Blink
 else if(operation == '2')
 {
 digitalWrite(13, HIGH);
 delay(500);
 digitalWrite(13, LOW);
 delay(500);
 }
}

Java Client


// Yu Hin Hau
// Java to Arduino Communication (Client)
// 5/18/2012
//

import java.util.Scanner;
import jssc.SerialPort;
import jssc.SerialPortList;
import jssc.SerialPortException;
public class arduinoComm2
{

 public static void main(String[] args) throws InterruptedException
 {

//Define Port
 SerialPort serialPort = new SerialPort("COM11");

 try
 {
 //Open Serial Port and set Parameters
 serialPort.openPort();
 serialPort.setParams(9600,8,1,0);

//Create Scanner to read from Console
 Scanner reader = new Scanner(System.in);

 while(true)
 {
 System.out.print("Operation (0 = Off / 1 = On / 2 = Blink ): ");

 if(reader.hasNext())
 {

/*Remember that through Serial, we are sending bytes through,
 * therefore, we must convert the char input we got
 * into byte form. In another word, the value reprsented in
 * the system encoding, aka ASCII code. 0 is 48, 1 is 49,
 * 2 is 50... luckily, we can type cast in Java. Mess around
 * with this program to see the different ASCII representation
 * for each of your character input!
 */

String buf = reader.next();
 char buf2[] = buf.toCharArray();

serialPort.writeByte((byte)buf2[0]);

System.out.println((byte) buf2[0] + " <= sent!");
 }

 }

 }
 catch (SerialPortException ex)
 {

System.out.println(ex);

}
 }

}

I will probably try to do a both 2-way communication example in the next couple days, if not , then after the Global Space Exploration Conference at DC 😀

Advertisements

14 thoughts on “[Engineering] Arduino to Java Serial Communication 2

  1. Pingback: [Engineering] Arduino to Java Serial Communication | Billwaa's Blog

    • Try using Processing instead, it is still programmed in Java, but it’s a lot easier and faster in terms of GUI. And there’s lot of tutorials on how to communicate with Arduino through it’s standard Serial library. Actually, Arduino is based on Processing, so you will find the two similar. http://processing.org/

  2. I have one question.

    My arduino is using COM8 and meanwhile we are doing serial communication with java code so same port number should be there.

    But in doing so, java code shows error that port is busy. If we do not communicate on single port how can communication be happened. ?

    • If I understand what you are saying, close the Serial Monitor in the Arduino IDE before you interface with Java. Only 1 program can access that port on the same computer at a time. 🙂

  3. hai, I wanna ask anyway that can Java send something to Arduino without Java side hitting the enter key? because I’ve make an interface where i click a button and something to Arduino but it only work when i hit enter on the console. Anyway to solve this?

    • You should be able to just skip the Scanner class / the console and just do “serialPort.writeByte(buffer);” in your GUI button’s call back function with buffer containing the byte data of whatever you are trying to send.

      • Hi Billwaa!
        I am very new to Java, but I think I made it like You sad to matt, but it does not work. Would be so kind to have a look at my code? I can send it to You, or can I paste here?
        Thanks!

      • Sure, you can post it here. Though I might not be able to get it to work, since I don’t really use Java anymore and I am not that good at it to start with lol

  4. Thank you Sir. Your advise for closing Arduino Comm Monitor really save my a lot of time. I was stuck there for 2-3 hrs. Thank you Very much.

  5. I tried to define a string value (e.g String buf = “2”) instead of getting the value in console. But it did not work. Could you give me some advise?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s