Sending data from a Java application to Arduino Uno

Following my previous post, I made a test if I’m able to send data from a Java program to an Arduino board. The main thing to remember from this exercise:

  • Ensure the Java application doesn’t send its data faster than the Arduino board can handle.
  • String comparison on Arduino was a lot slower than comparing byte data (integer) in the Arduino code; as a consequence the Java application had to wait approximately 5 times longer to start its next iteration. After reading a bit about this, it seems that Arduino supports ‘String’ data type, but one can better use a character array instead.

Java application:

package be.familievandamme.projects.ka350i.arduino;

import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.util.Enumeration;

/**
 * Writes integer values (0 or 1) to an Arduino board. Depending on the values
 * received, the Arduino board should light up LEDs or shut off LEDs.
 * 
 * @author Maarten Van Damme
 *
 */
public class ArduinoWriteTest {

  static SerialPort serialPort;
  private final static String PORT_NAMES[] = { "COM4" };
  private static OutputStream output;
  private static final int TIME_OUT = 2000;
  private static final int DATA_RATE = 9600;

  public static void main(String[] args) {
    new ArduinoWriteTest();
  }

  public ArduinoWriteTest() {

    CommPortIdentifier portId = null;
    @SuppressWarnings("unchecked")
    Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();

    // Find an instance of serial port as set in PORT_NAMES.
    while (portEnum.hasMoreElements()) {
      CommPortIdentifier currPortId = portEnum.nextElement();
      for (String portName : PORT_NAMES) {
        if (currPortId.getName().equals(portName)) {
          portId = currPortId;
          break;
        }
      }
    }
    if (portId == null) {
      System.out.println("Woops, could not find COM port.");
      return;
    }

    try {

      System.out.println(this.getClass().getName());
      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);

      // For byte data handling
      output = serialPort.getOutputStream();
      // For string data handling
      // output = new PrintWriter(serialPort.getOutputStream());

      for (int i = 0; i < 100; i++) {

        // Alternate 0 and 1 values
        int intValue = (i % 2 == 0 ? 0 : 1);
        System.out.println("Sending value " + intValue + " to Arduino Uno.");

        output.write(intValue);
        output.flush();

        // Tweak the value below to ensure that the Arduino can run
        // through the entire code in the 'loop' function once.
        // If the value is too small, Arduino will get more data it can
        // chew, and will miss iterations. If the value is too high, the
        // program will be slow.
        Thread.sleep(25);

      }
      output.close();
      serialPort.close();

    } catch (Exception e) {
      System.err.println(e.toString());
    }
  }
}

Arduino code:

/**
   Reads an integer value from Serial.
   @Author Maarten Van Damme
*/
int data = 0;
int greenLed = 10;
int redLed = 11;

void setup() {
  Serial.setTimeout(200);
  Serial.begin(9600);
  pinMode(greenLed, OUTPUT);
  pinMode(redLed, OUTPUT);
}
/* Send text to the serial output */
void loop() {
  //Only handle data if data is received (when no data is received, data will be -1
  if (Serial.available() > 0) {

    data = Serial.read();
    Serial.print("Serial value read: ");
    Serial.println(data);

    //Depending on the wiring of the led, the led will be on or off for value 1
    if (data == 1 )
    {
      digitalWrite(greenLed, HIGH);
      digitalWrite(redLed, LOW);
    }
    //Depending on the wiring of the led, the led will be on or off for value 0
    else if (data == 0) {
      digitalWrite(greenLed, LOW);
      digitalWrite(redLed, HIGH);
    }
  }
  else
  {
    //Do nothing. Data value remains the same until new serial data enters.
  }
  //delay(20);

}

Good evening!

Maarten

Leave a Reply

Your email address will not be published. Required fields are marked *