Skip to content

Arduino and Java

Arduino

Arduino is a free popular platform for embedded programming based on a simple I/O board easily programmable. Interfacing it with Java allow us to create sophisticated interfaces and take advantages from the several API available in the Java ecosystem.

I’m following the original Arduino and Java interfacing tutorial by Dave Brink but in a more practical approach and with more details.

Step 1) Install the Arduino IDE

This is not a completely mandatory step but it will easy a lot our work. Our program will borrow some Arduino IDE libraries and configurations  like which serial port it is using and at which boud rate. At the moment I wrote this tutorial the version of Arduino IDE was 0013.

Step 2) Prepare your Arduino

Connect your Arduino to the serial port in your computer. Here I’m connecting my Arduino with my laptop throught a USB.

Arduino

Make sure your Arduino IDE is configured and communicating well if your Arduino. Let put on it a little program that sends to us a mensage:

void setup(){
  Serial.begin(9600);
}

void loop(){
  Serial.println("Is there anybody out there?");
  delay(1000);
}

Step 3) Install RXTX Library

We will use some libraries to acess the serial port, some of them relies on binary implementations on our system. Our first step is to install the RXTX library (Java CommAPI) in your system. In a Debian like Linux you can do that by:

sudo apt-get install librxtx-java

Or using a graphical package tool like Synaptic:

installing rxtx

For others systems like Windows see the RXTX installation docs.

Step 4) Start a new NetBeans project

Again, this is not a mandatory step but will easy a lot our work. NetBeans is a free and open source Java IDE that will help us to develop our little application. Create a new project at File → New Project and choose at Java at Categories and Java Application at Projects.

netbeans new project

Chose a name for your project. I called mine SerialTalker.

name your project

At the moment I wrote this tutorial I was using Netbeans version 6.5 and Java 6 update 10 but should work as well on newer and some older versions

Step 5) Adding Libraries and a Working Directory

On NetBeans the Projects tab, right-click your project and choose Properties.

libraries

On the Project Properties window select the Libraries on the Categories panel.

Netbeans project libraries

Click the Add JAR/Folder button.

arduino directory

Find where you placed your Arduino IDE installation. Inside this directory there’s a lib directory will some JAR files. Select all them and click Ok.

jars libraries

As we want to borrow the Arduino IDE configuration the program needs to know where is they configuration files.  There’s a simple way to do that.

Still in the Project Properties window select Run at Categories panel. At Working Directory click in the Browse button and select the directory of your Arduino IDE. Mine is at /home/silveira/arduino-0013.

Working directory

You can close now the Project Properties window. At this moment in autocomplete for these libraries are enable in your code.

netbeans autocomplete

Step 6) Codding and running

Here is the code you can replace at Main.java in your project:

package serialtalk;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.InputStream;
import java.io.OutputStream;
import processing.app.Preferences;

public class Main {
    static InputStream input;
    static OutputStream output;

    public static void main(String[] args) throws Exception{
        Preferences.init();
        System.out.println("Using port: " + Preferences.get("serial.port"));
        CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(
                Preferences.get("serial.port"));

        SerialPort port = (SerialPort)portId.open("serial talk", 4000);
        input = port.getInputStream();
        output = port.getOutputStream();
        port.setSerialPortParams(Preferences.getInteger("serial.debug_rate"),
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);
        while(true){
            while(input.available()>0) {
                System.out.print((char)(input.read()));
            }
        }
    }
}

Now just compile and run (with your Arduino attached in your serial port and running the program of step 2).

voillá

There is. Now you can make your Java programs to talk with your Arduino using a IDE like NetBeans to create rich interfaces.

Published inenglish

95 Comments

  1. Marc Marc

    Same problem
    Since the serialport id declared static I cannot fill a Jtextfield with the data read from the serial port in a GUI in netbeans.
    The error message “non-static member cannot … from a static”
    How can that be solved?


    Kam:

    I’m trying to create a GUI with this using Swing in Netbeans.I created a JForm and put in a text box. Now I want to update the text in the text field from the serial communication.
    I created a method and used this to convert to String:String text = Integer.toString(input.read());
    But now how do I invoke textField1.setSet()? Where do I invoke it? I tried creating a method, and invoking it there but I’m getting no love. I tried invoking it from main() but I get “non-static member cannot…from static etc” <-hate this
    Haven’t programmed in Java for 2 years so I’m still fresh.

    • Alex Alex

      You need to make the main class instantiate itself from the main method.

      f.ex
      public class Example{

      //code omitted
      public static void main(String[] args)
      {
      //this gives you the error you get
      doSomething();

      //this should work
      Example ex = new Example();
      ex.doSomething();
      }

      public void doSomething()
      {
      }
      }

  2. Karl Karl

    Hi, everything works great but more than only see what’s I wrote in the Arduino, I’d like to write on it from netbeans (like using output.write) but it doesn’t work.
    Did someone tried and success doing it ?!

    • Bob Butcher Bob Butcher

      I also got the java software to read the serial data that was being output by the Arduino. As I understand what you want to do, you need to program the Arduino to receive data as well as to just send a string once a second. There is another product called Labjack that has been on the market for many years, although more expensive and possibly less powerful than Arduino. It comes pre-programmed to send and receive data over the serial port. Using Java, or many other languages it can receive commands, act on the command, and return data. If someone were to write an operating system, sort of a BIOS, for Arduino then it could do the same thing.

  3. Marcelo Marcelo

    Olá Silveira, belo artigo!!!
    Agora, preciso de sua ajuda: estou fazendo uma aplicação para arduino, e preciso controlar dois servo motores, mas como eu faço isso usanto a porta serial ?
    com um servo deu certo.. já ta pronto, mas e com dois servos ? como eu faço a divisão da informação para enviar via serial…. para controlar cada servo independente. Eu utilizo o arduino, 2 servos, e a linguagem de programação é Java… fico no aguardo. abraços !!!

  4. В текущем годе запланировано несколько повешений цен на газ воду и электричество!
    Купи себе неодимовый магнит и реши свои проблемы!
    Остановить счетчик воды!
    Остановить электросчетчик!
    Остановить газовый счетчик!

    Мечта любого домовладельца может стать реальностью!

    Я покупал магниты большей мощности здесь,
    Будите обращаться напишите что вы от “#5633454”.

    Удачной экономии в этом году!

  5. kamila kamila

    Very coll.

    Now i can started with my arduino.
    Tanks ,now is clear.

  6. jelle jelle

    This is great, thanks you kindly!

  7. Z.K. Z.K.

    I followed your tutorial, but I keep getting this error:

    init(java.lang.String) in processing.app.Preferences cannot be applied to () Preferences.init();

    I am new to Java so I am not sure what is going on. I followed all the steps in the tutorial.

    • Sandra Costa Sandra Costa

      Hi Z.K.

      Can you tell what you did to overcome this error, please?

      Sandra

  8. Z.K. Z.K.


    Z.K.:

    I followed your tutorial, but I keep getting this error:
    init(java.lang.String) in processing.app.Preferences cannot be applied to () Preferences.init();
    I am new to Java so I am not sure what is going on. I followed all the steps in the tutorial.

    Okay, I got the program to compile now by the tips on Item #24 which were very useful. But, how do I write data to the serial port? There does not seem to be any write method on the serial port object.

    • Bob Butcher Bob Butcher

      The problem is with the Arduino running Hello World. All it does is send the string once per second, it is not programmed to listen or receive data. You need to change the sketch to something that can receive as well as send data. I found a sketch that would at least be a good start. Check out
      wilson.serialio.ver43.txt at the website:

      http://userwww.sfsu.edu/~infoarts/technical/arduino/wilson.arduinoresources.html

    • Ben Ben

      Hello
      I was wondering how you solved the problem with the “preferences”, what is this “item #24”?

  9. thony thony

    oye seguí todos los pasos y me funciona muy bien, soy nuevo en esta área y tengo una duda, como puedo usar digitalWrite??? ya que estuve intentando pero no logre hacer alguna referencia a este, necesito importar una librería en especifico o como?? lo que pasa que estoy haciendo un proyecto en el cual utilizo una matriz de leds de 8×8 y con esa función me parece logro encender y apagar leds de forma mas sencilla y no quiero utilizar el entorno de arduino prefiero netbeans, podrías ayudarme??

  10. thony thony


    thony:

    oye seguí todos los pasos y me funciona muy bien, soy nuevo en esta área y tengo una duda, como puedo usar digitalWrite??? ya que estuve intentando pero no logre hacer alguna referencia a este, necesito importar una librería en especifico o como?? lo que pasa que estoy haciendo un proyecto en el cual utilizo una matriz de leds de 8×8 y con esa función me parece logro encender y apagar leds de forma mas sencilla y no quiero utilizar el entorno de arduino prefiero netbeans, podrías ayudarme??

    hey I followed all the steps and it works very well, I’m new to this area and I have a question, as I can use digitalWrite?? because I was trying but failed to make any reference to this, I need to import a specific or bookstore? what happens I’m doing a project that uses an array of LEDs in 8 × 8 and I think achieving that function on and off leds in a more simple and do not want to use the arduino environment prefer netbeans, could you help me?
    excuse my bad English

  11. предлагаем Вам записаться на курсы Французского языка. Современные занятия с русскоговорящими и франкоговорящими преподавателями. По окончании курса обучения – БЕСПЛАТНОЕ общение с носителями языка.

  12. Great tutorial, based on RXTX we have developed a JAVA API which give access to many arduino features directly in JAVA. You can check the JArduino project on github for more information (https://github.com/ffleurey/JArduino).
    Cheers!

  13. Thiago Thiago

    Boa tarde Silveira…
    Otimo tutorial parabens…
    Sou estudante de engenharia eletrica em SP e atualmente me encontro super interessado em projetos com arduino.
    Neste tutorial eu consegui fazer tudo plenamente,mas estou com uma duvida e acho que vc pode me ajudar…
    Apos feita a comunicação entre Java e arduino ,como eu faço para controlar o arduino atraves de botoes e funcoes com java/netbeans??
    Desde ja agradeço. se precisar do meu e-mail e so pedir .valeu ,super abraço.

  14. Thiago Thiago

    Bom dia Silveira….

    Sou o Thiago do comentario acima….

    vc pode me passar um codigo em java exemplificando o modo de acender um Led no arduino atraves de um evento de botão no java???

    tentei de varias maneiras e não estou conseguindo!!
    Por favor se vc me ajudar irei ficar muito Agradecido.
    Um abração!!!vlw!!!!

  15. […] things are awesome with wicked community support (Just like linux) here is a link to the serial communication tutorial on Linux and also a generic tutorial supplied by the manufacturer. LD_AddCustomAttr("AdOpt", […]

  16. mudit thakkar mudit thakkar

    nit(java.lang.String) in processing.app.Preferences cannot be applied to () Preferences.init();

    this error message i got after following all the steps……please suggest me what can i do..i will very glad if u reply at the earliest.
    email: tmudit@gmail.com

    • I also have the same problem like you, I traced back the commented and some body said that you can comment that line, and the code still work.
      But I cant even compile it now!

  17. Felipe Felipe

    hey this works fine until the arduino 0016 i imported the library from the arduino 0016 to netbeand and programe the arduino uno with 1.0.1 and work fine thanks for the tutorial

  18. mark mark

    hey that’s cool.do you know how can we send parameter to arduino for ex :(turn on light or turn off light)

  19. wicak wicak

    some body help me please ..
    i have to control motor stepper with arduino and java as a processing in my computer, but i had bought the arduino and the stepper,,

  20. Furqan Furqan

    I get error ” Preferences.init();”
    i m using atmega 256
    Plz can any one help me
    Thanks

  21. Divya Divya

    i found an error in Preferences.init()

  22. Divya thomas Divya thomas

    having an error in preference.init()

  23. Lewis Lewis

    ant -f C:\\Users\\mhsec\\Documents\\NetBeansProjects\\Arduino -Djavac.includes=arduino/Arduino.java compile-single
    init:
    Deleting: C:\Users\mhsec\Documents\NetBeansProjects\Arduino\build\built-jar.properties
    deps-jar:
    Updating property file: C:\Users\mhsec\Documents\NetBeansProjects\Arduino\build\built-jar.properties
    Compiling 1 source file to C:\Users\mhsec\Documents\NetBeansProjects\Arduino\build\classes
    C:\Users\mhsec\Documents\NetBeansProjects\Arduino\src\arduino\Arduino.java:9: class Main is public, should be declared in a file named Main.java
    public class Main {
    C:\Users\mhsec\Documents\NetBeansProjects\Arduino\src\arduino\Arduino.java:14: cannot find symbol
    symbol : variable COM3
    location: class arduino.java.Main
    Preferences.init(COM3);
    2 errors
    C:\Users\mhsec\Documents\NetBeansProjects\Arduino\nbproject\build-impl.xml:949: The following error occurred while executing this line:
    C:\Users\mhsec\Documents\NetBeansProjects\Arduino\nbproject\build-impl.xml:268: Compile failed; see the compiler error output for details.
    BUILD FAILED (total time: 10 seconds)

    Help?

    Would be much appreciated

    Regards

    Lewis Joyce

    Lewis.joyce@rootsecurity.co.uk

  24. Futur_ing Futur_ing

    Thank you for you tuto.. it works Great for me.
    But can you PLEASE tell me haw can i SEND a something to ARDUINO via Java ?

    i want to send a A or B to arduino so that i ‘ll activate or desactivate a led wonce it gets the caracter but in vain .. i need help plzzz.

  25. t.tirupathi t.tirupathi

    Hi,
    I am using arduino 1.0.6, and arduino uno board, I have followed the steps given by you,
    but I am getting the following error.

    “method init in class preferences can not be applied to given types.”

    If I comment this, am getting exception as

    “Exception in thread “main” gnu.io.NoSuchPortException
    at gnu.io.CommPortIdentifier.getPortIdentifier(CommPortIdentifier.java:218)
    at serialtalk.SerialTalk.main(SerialTalk.java:22)”

    Can you please help me.
    Thank you.

  26. Lorenzo Lorenzo

    Hi, I’ve a problem with Preferences.init() I’ve already tried to give a string like argument but it didn’t work. What shall I do?

  27. Hannes Adam Hannes Adam

    please send a hint for arduino mega IDE java download width
    my old pc
    many thanks

Leave a Reply to khoa Cancel reply

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