2

I'm trying to communicate Arduino with Java i'm using JSerialComm for this. I'm trying to turn on and off a led with java using a GUI. The problem i have is that when i try to turn on the Led it flashes on and and instantly off, but i'm trying to keep it on or off with the buttons. When i use Serial Monitor in Arduino and write 1 or 0 it works fine but when using GUI with buttons it doesn't work for some reason.

Ardiuno Code:

#define LED 13

int input;

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


void loop()
{
      

 if (Serial.available() > 0) {

    input = Serial.read();
    Serial.println(input);
    

    if (input == '1') {


       Serial.println("Start");
       digitalWrite(LED, HIGH);
      
    } else if (input == '0') {

        Serial.println("Stop);
        digitalWrite(LED, LOW);

      
    }
  
 }
}

Java Code Ardiuno Connection where we make the Connection and Classes for Turning on a led and off:

import com.fazecast.jSerialComm.SerialPort;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ArdiunoConnection {

    SerialPort sp;


    public boolean getConnection() {

        sp = SerialPort.getCommPorts()[0];
        sp.setComPortParameters(9600, 8, 1, 0);
        sp.setComPortTimeouts(SerialPort.TIMEOUT_WRITE_BLOCKING, 0, 0);
        return sp.openPort();

    }

    public void turnOn() throws IOException {


        if (getConnection()) {

            sp.getOutputStream().write('1');
            sp.getOutputStream().flush();
            System.out.println("Sent number: " + 0);
            sp.closePort();

        } else {

            System.out.println("Error");


        }

    }

    public void turnOff() throws IOException {

        if (getConnection()) {


            sp.getOutputStream().write('0');
            sp.getOutputStream().flush();
            System.out.println("Sent number:" + 0);
            sp.closePort();


        } else {


            System.out.println("Error");


        }
    }





}

Java code for GUI where we make a ActionListener that performs the Ardiuno off or on

import com.fazecast.jSerialComm.SerialPort;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;



public class Systeem extends javax.swing.JFrame {

    boolean light;
    ArdiunoConnection obj;
    private JButton btnLight;
    private JPanel MainPaneltje;


    public Systeem() {

        setContentPane(MainPaneltje);

        btnLight.setText("Starten");
        obj = new ArdiunoConnection();


        setTitle("GUI");
        setSize(600, 400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setVisible(true);


        btnLight.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                try {


                    if (light) {

                        btnLight.setText("Starten");
                        obj.turnOn();
                        light = false;

                    } else {

                        btnLight.setText("Stoppen");
                        obj.turnOff();
                        light = true;


                    }



                } catch (IOException ex) {


                    Logger.getLogger(System.class.getName()).log(Level.SEVERE, null, ex);

                }
            }
        });
    }


    public static void main(String[] args) {


        Systeem gui = new Systeem();



    }



}
2
  • 1
    In the Java code, I would try opening the serial port only once and keeping it open the whole time your program is running. Commented May 28, 2022 at 14:05
  • @JohnnyMopp Thanks, i added the Connection code in a constructor and used getConnection() to return isOpen() so it just checks if the Serial is already open. Commented May 28, 2022 at 16:17

1 Answer 1

1

The normal configuration for the Arduino is to restart when a serial connection is created. In your java class methods for turnOn/turnOff, you use:

if (getConnection())

This causes the getConnection() method to be called, and this method opens the serial port, so the Arduino restarts, and so the LED goes off.

Two suggestions:

  1. If you need to test the state of the serial port, use if (sp.openPort()) instead of if (getConnection())
  2. But better is to not close the serial port connection while you are using the program, so it does not have to be opened again. There is no need to have the sp.closePort() statement in the turnOn/turnOff methods. Create a ArduinoConnection.close() method instead, and call it when your GUI exits.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.