Control an Arduino with Java

You can use the JArduino (Java-Arduino) library, which provides a Java API to control your Arduino using serial port (using a USB cable, or wireless devices behaving as serial ports from a software point of view), UDP (via an ethernet shield). All the code related to communication between Java and Arduino is managed internally by the library.

Here is a Java sample to blink an LED:

public class Blink extends JArduino {

public Blink(String port) {
    super(port);
}

@Override
protected void setup() {
    // initialize the digital pin as an output.
    // Pin 13 has an LED connected on most Arduino boards:
    pinMode(DigitalPin.PIN_12, PinMode.OUTPUT);
}

@Override
protected void loop() {
    // set the LED on
    digitalWrite(DigitalPin.PIN_12, DigitalState.HIGH);
    delay(1000); // wait for a second
    // set the LED off
    digitalWrite(DigitalPin.PIN_12, DigitalState.LOW);
    delay(1000); // wait for a second
}

public static void main(String[] args) {
    String serialPort;
    if (args.length == 1) {
        serialPort = args[0];
    } else {
        serialPort = Serial4JArduino.selectSerialPort();
    }
    JArduino arduino = new Blink(serialPort);
    arduino.runArduinoProcess();
}
}

JArduino is available at: JArduino

Leave a Comment