Skip to main content Skip to local navigation

Easy Java + Arduino with Firmata (updated)

Easy Java + Arduino with Firmata (updated)

Blinking LED on the Arduino-compatible Grove Board
Blinking LED on the Arduino-compatible Grove Board

Arduino devices are commonplace in Engineering programs. Even if the profs don't use them, the students do. In Engineering programs, we often need to set up sensor monitoring or motor control systems. If students haven't worked with these in the first through third years of their programs, they are likely to encounter them in the "capstone" course in the final year of their program.

In my first year programming classes we alternate between using MATLAB and Java for linking a standard personal computer and an Arduino or Arduino-compatible board like the Seeed Studio Grove Beginner Kit for Arduino. The MATLAB exercises use vendor-supported hardware libraries. For Java, the solution is a little more complex. We could either have the students write custom C++ code for their Arduino and link to Java using a serial library like jSerialComm, or we could look for a simpler solution. That solution is Firmata. Here are two examples

  1. Simple Connection to the Board, and
  2. Blinking an LED

To use Firmata we need two components:

  1. On the Arduino we use the Standard Firmata program, built into the Arduino IDE.
  2. On the personal computer we use Kurbatov's Firmata4J library.

Here is a video for setting up a bare-bones Java project.

When importing in Maven, you need to import the following libraries: [update]

Windows 10 & 11 or
macOS M1 or M2 architecture
macOS Intel architecture
First importJSSC: io.github.java-native:jssc:2.9.4Firmata4J: com.github.kurbatov:firmata4j:2.3.8
2nd importFirmata4J: com.github.kurbatov:firmata4j:2.3.8SLF4J: org.slf4j:slf4j-jcl:1.7.3
3rd importSLF4J: org.slf4j:slf4j-jcl:1.7.3[nothing]
Libraries that need to be imported into your IntelliJ java project. Import them in this order (JSSC first in Windows, Firmata4j first in macOS) [update]

These libraries are:

  1. The Java Simple Serial Connector (JSSC), version 2.9.4. Used by Firmata4j to establish connections over USB. Use this search term within Maven
    • io.github.java-native:jssc:2.9.4 (external link) [only needed for Windows]
  2. The Firmata4J library, version 2.3.8. Use this search term within Maven
  3. The Simple Logging Facade for Java (SLF4J), version 1.7.3. Use this search term within Maven:

Simple Connection to Board

// Maven: com.github.kurbatov:firmata4j:2.3.8 
//          (https://mvnrepository.com/artifact/com.github.kurbatov/firmata4j/2.3.8)
// Also we need to manually re-install SLF4J : org.slf4j:slf4j-jcl:1.7.3 
//          (https://mvnrepository.com/artifact/org.slf4j/slf4j-jcl/1.7.3)
import org.firmata4j.firmata.*;
import org.firmata4j.IODevice;

public class SimpleExample {
    public static void main(String[] args) {
        String myPort = "/dev/cu.usbserial-0001"; // modify for your own computer & setup.

        IODevice myGroveBoard = new FirmataDevice(myPort); // using the name of a port

        try {
            myGroveBoard.start();       // start comms with board;
            System.out.println("Board started.");

            myGroveBoard.ensureInitializationIsDone();

            myGroveBoard.stop();        // finish with the board.
            System.out.println("Board stopped.");
        }
        catch (Exception ex){
            System.out.println("couldn't connect to board.");
        }
    }
}
Video showing the RX and TX LED lights confirming that the Java program and Arduino board "spoke" to one another.

Blinking LED

On the Grove Beginner Kit for Arduino, we have a large LED on Pin D4. Your own board might have one on a different pin, like Pin D13. Check your board.

Here we'll turn on the D4 LED for 500 milliseconds and then turn it off.

// Maven: com.github.kurbatov:firmata4j:2.3.8
//          (https://mvnrepository.com/artifact/com.github.kurbatov/firmata4j/2.3.8)
// Also we need to manually re-install SLF4J : org.slf4j:slf4j-jcl:1.7.3
//          (https://mvnrepository.com/artifact/org.slf4j/slf4j-jcl/1.7.3)
import org.firmata4j.firmata.*;
import org.firmata4j.IODevice;
import org.firmata4j.Pin;
import java.io.IOException;

public class SimpleExampleRead {
    public static void main(String[] args)
    throws IOException
    {
        String myPort = "/dev/cu.usbserial-0001"; // modify for your own computer & setup.

        IODevice myGroveBoard = new FirmataDevice(myPort); 

        try {
            myGroveBoard.start();       // start comms with board;
            System.out.println("Board started.");
            myGroveBoard.ensureInitializationIsDone();
        }
        catch (Exception ex) {
            System.out.println("couldn't connect to board.");

        }
        finally {
            var myLED = myGroveBoard.getPin(4);
            myLED.setMode(Pin.Mode.OUTPUT);

            // LED D4 on.
            myLED.setValue(1);

            // Pause for half a second.
            try {
                Thread.sleep(500);
            }
            catch(Exception ex){
                System.out.println("sleep error.");
            }
            // LED D4 off.
            myLED.setValue(0);

            myGroveBoard.stop();        // finish with the board.
            System.out.println("Board stopped.");

        }
    }
}
Blinking an LED on the Arduino compatible board. D4's LED will turn on for half a second, then turn off.


The following is a list of pin mappings that relate to the Grove Beginner Kit for Arduino. Numeric values are a little difficult to figure out. Pin Modes are described here.

Arduino pin nameDefault Grove FunctionLocationFirmata NumberTestedNote
D0RX for USBcentre module0noDon't use this. It's for the USB / UART
D1TX for USB1noDon't use this. It's for the USB / UART
D2connector shared with D3centre module2noRegular Grove cable
D3Temperature & Humid.Middle Right3no-
D4Big Red LEDUpper left4Yes-
D5BuzzerUpper left5Yesuse Firmata PWM or Servo mode to activate it.
D6ButtonLower left6Yes-
D7connector shared with D8centre module7noRegular Grove cable
D8connector shared with D7centre module8noModified Grove cable
D9On yellow UNO headercentre module9noconnection
D10On yellow UNO headercentre module10noShield connection
D11On yellow UNO headercentre module11noShield connection
D12On yellow UNO headercentre module12noShield connection
D13Green LEDBottom Centre13Yes-
A0PotentiometerBottom left14Yes-
A1connector shared with A0centre module15noModified Grove cable
A2Soundupper right16Yes-
A3connector share with A2centre module17noModified Grove cable
A4On yellow UNO headercentre module18noShield connection
A5On yellow UNO headercentre module19noShield connection
A6LightUpper right20YesOut of bounds if UNO. Flash StandardFirmata as Nano.
A7connector shared with A6centre moduleTBDnoModified Grove cable
------
I2COLED DisplayMiddle leftn/ayessupported
I2CAir PressureLower rightTBDno-
I2CAccelerometerLower rightTBDnosee this link.
UARTconnectorcentre moduleTBDnoRegular Grove cable
Pin and function mappings for the Grove Beginner Kit for Arduino with respect to Firmata.

Here is another video overview of using Firmata and Java.

Firmata and Java (longer video)

Warnings and Errors

Most of you will get the 2.5 vs 2.3 version warning. This warning is fine. You can safely ignore it.

This warning happens all the time. Don't worry about it.

Some of you will get a runtime error "index 4 is out of bounds for length 0" or some variant of this. The error doesn't happen at compile time. It happens at run time (pressing the green triangle). You need to place your pin setup code after your board startup code. Like this (the specific code will look different in your program).

runtime error : index 4 is out of bounds for length 0.
runtime error : index 4 is out of bounds for length 0. Place your pin initialization code after your board startup and initialization routine.

a pen

James Andrew Smith is a Professional Engineer and Associate Professor in the Electrical Engineering and Computer Science Department of York University's Lassonde School, with degrees in Electrical and Mechanical Engineering from the University of Alberta and McGill University.  Previously a program director in biomedical engineering, his research background spans robotics, locomotion, human birth and engineering education. While on sabbatical in 2018-19 with his wife and kids he lived in Strasbourg, France and he taught at the INSA Strasbourg and Hochschule Karlsruhe and wrote about his personal and professional perspectives.  James is a proponent of using social media to advocate for justice, equity, diversity and inclusion as well as evidence-based applications of research in the public sphere. You can find him on Twitter. Originally from Québec City, he now lives in Toronto, Canada.