Send data to Teensy3.6 using Java

Hello,

I`m working on an interface, in JavaFX, that needs to send 10 integers (via a vector or something) to the Teensy.

Basically i have 10 Sliders, after i move each slider to a position, i need to hit the button "Send" and this interface should send those 10 numbers to the arduino, and after that, the arduino will use these numbers to set some PWMs (the teensy part is easy, ive worked on arduino before so it`s okay).

The problem is getting the java interface work with Teensy... i`ve been searching the internet and found something about RXTX library, JSerialComm.. etc..

I`m new to java, but i think i can easily understand the code.

To make the interface and java code im using Intellij and Scene Builder. Ive done 1 slider, the send button and the code that saves the integer of a slider (i just need to upgrade it to 10 sliders). Now i need to send that integer to arduino whenever the send button is clicked.

Can somebody help me?

Thanks in advance!

Hello,

I`m working on an interface, in JavaFX, that needs to send 10 integers (via a vector or something) to the Teensy.

Basically i have 10 Sliders, after i move each slider to a position, i need to hit the button "Send" and this interface should send those 10 numbers to the arduino, and after that, the arduino will use these numbers to set some PWMs (the teensy part is easy, ive worked on arduino before so it`s okay).

The problem is getting the java interface work with Teensy... i`ve been searching the internet and found something about RXTX library, JSerialComm.. etc..

I`m new to java, but i think i can easily understand the code.

To make the interface and java code im using **Intellij** and **Scene Builder** on **Windows 10**. Ive done 1 slider, the send button and the code that saves the integer of a slider (i just need to upgrade it to 10 sliders). Now i need to send that integer to arduino whenever the send button is clicked.

Can somebody help me?

Thanks in advance!

so long as you don't require to transmit large amounts of data serial is probably the simplest using jSerialComm

for the arduino have a read thru

I have never used jSerialComm but have implemented similar applications in C++, C# and VB using the SerialComm component of Visual studio

overview:

start a Server on Arduino and wait for clients. parse what client send. see ChatServer example

open a Socket in Java and send data to Arduino.

Okay... so we will stick to jserialcomm...

At the end of this project, this interface should be able to send 10 integers to the Teensy. But for now we will stick to only 1 integer.

Can you help me with a code in Java that sends one integer to arduinos serial monitor (i will use teensy, but its the same thing). After that i will try to combine your code with the slider and the send button.

Someone told me to use jSerialComm... But i do not get it. Also, i do not have a wifi shield. It`s a teensy, so i need to communicate with it via a usb cable.

I know very little Java and it is a while since I used JRuby. When I did I used JSSC for serial communication - it worked well.

For receiving data on the Arduino have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

...R

for a start try this simple Java program which lists the COM ports

// JSerialComm - list COM ports on PC
import com.fazecast.jSerialComm.*;
public class ListCOMports {
  public static void main(String[] args) { 
   System.out.println("List COM ports");
   SerialPort comPorts[] = SerialPort.getCommPorts();
       for (int i = 0; i < comPorts.length; i++)   
          System.out.println(comPorts[i].getDescriptivePortName());
   }
}

when I run it on my PC I get

List COM ports
Communications Port (COM1)
USB-SERIAL CH340 (COM9)
USB-SERIAL CH340 (COM23)
USB-SERIAL CH340 (COM10)

At this moment i`m at work, so i will try tonight. Thanks for helping me out, little by little

@Xeyow, I see you cross-posted. I also see you have been a member of this forum since 2014. Being a member that long you undoubtedly know cross-posting is verboten. Which means you have deliberately wasted your time and the time of those trying to help you. Please spend your timeout carefully considering how selfish you have been.

Threads merged.

this Java program transmits an integer via srial port and display any return message

// jSerialComm read integer and transmit to COM port

// java -cp D:\Programming\JAVA\JSerialComm\jSerialComm-1.3.11.jar;.  SerialTransmitInteger

import com.fazecast.jSerialComm.*;
import java.util.*;

public class SerialTransmitInteger {
  public static void main(String[] args) { 
  Scanner console = new Scanner(System.in);
   System.out.println("List COM ports");
   SerialPort comPorts[] = SerialPort.getCommPorts();
       for (int i = 0; i < comPorts.length; i++)   
          System.out.println("comPorts[" + i + "} = " + comPorts[i].getDescriptivePortName());
  int port = 1;
  comPorts[port].openPort();
  comPorts[1].setBaudRate(115200);
  try {
    while (true)
    {
      // transmit integer to serial port
      System.out.print("enter an integer ");
      int test = console.nextInt();                // read intger
      //System.out.println("you entered " + test);   // display it
      byte[] writeBuffer=(Integer.toString(test) + "\n").getBytes();
      comPorts[port].writeBytes(writeBuffer, writeBuffer.length);
     // read serial port for response and display it
      while (comPorts[port].bytesAvailable() == 0)
         Thread.sleep(20);
      byte[] readBuffer = new byte[comPorts[port].bytesAvailable()];
      int numRead = comPorts[port].readBytes(readBuffer, readBuffer.length);
      System.out.print("Read " + numRead + " bytes from COM port: ");
       for (int i = 0; i < readBuffer.length; i++)   
           System.out.print((char)readBuffer[i]);
       System.out.println();
     }
  } catch (Exception e) { e.printStackTrace(); }
  comPorts[1].closePort();  
}
}

the arduino program reads an nteger from serial port and echos it back

// SERIAL: read and echo integer value
void setup() {
  // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.setTimeout(60*60*1000ul);
}
void loop() {
//  Serial.print("enter integer ? ");
  int data=Serial.parseInt();
  Serial.print("Arduino received integer = ");
  Serial.println(data);
 }

a run gives

D:\Programming\JAVA\JSerialComm>java -cp D:\Programming\JAVA\JSerialComm\jSerialComm-1.3.11.jar;.  SerialTransmitInteger
List COM ports
comPorts[0} = Communications Port (COM1)
comPorts[1} = USB-SERIAL CH340 (COM9)
enter an integer 678
Read 32 bytes from COM port: Arduino received integer = 678

enter an integer 567
Read 32 bytes from COM port: Arduino received integer = 567

enter an integer 234
Read 32 bytes from COM port: Arduino received integer = 234

enter an integer

Using the code above i get no errors in the java, but on the teensy`s serial monitor i get this (i added a delay(1000) and commented the serial.SetTimer line cus nothing happend otherwise):

Arduino received integer = 0. every 1000ms...

It seems that the java code sends that integer because after entering an integer i am greeted with the message again: "enter an integer", but the teensy is unable to get that value.

What could be the problem?

if you remove the Serial.setTimeout() the parseInt() will keep returning after the timeout period (1 second?) with 0
how many COM ports do you have connected to the PC?
I suspect the java program is not opening the correct COM port
where is the display Arduino received integer = 0 appearing (on the serial monitor)?
ensure you know which port the Teensey is connected too and set int port = 2; up to that port (remember Java arrays indexes from 0)
give us a printout of the java console?

Arduino received integer 0 shows up on the serial monitor of the Arduino.

the list of comports that appear in java shows that Teensy (USB SERIAL) is on the 2nd position, so i set port to 1.

I will post the code when i get home.

Starting from tomorrow i will have my teensy with me, while i work!

if you have the Arduino serial monitor open the Java program will list the COM port but will be unable to open it
we should check the result of openPort() for sucess or fail, e.g. update the code of post #11

  if(!comPorts[port].openPort())
    {  System.out.println("unable to open port " + comPorts[port].getDescriptivePortName() + "\n"); return; };

if I have COM10 open in the serial monitor and run the Java program I get

> run SerialTransmitInteger
List COM ports
comPorts[0] = Communications Port (COM1)
comPorts[1] = USB-SERIAL CH340 (COM10)
unable to open port USB-SERIAL CH340 (COM10)

make sure you close the serial monitor before attempting to run the Java program

When i was doing those tests i was opening the serial monitor, after i was greeted with the message: "enter an integer" in java

close the serial monior
when java prompts enter an integer type a in int value on the Java console and hit
the arduino should receive it and echo the value back

I find it simplest to run from the Windows Command prompt, e.g.

D:\temp2>java -cp D:\Programming\JAVA\JSerialComm\jSerialComm-1.3.11.jar;.  SerialTransmitInteger
List COM ports
comPorts[0] = Communications Port (COM1)
comPorts[1] = USB-SERIAL CH340 (COM10)
enter an integer 678
Read 32 bytes from COM port: Arduino received integer = 678

enter an integer 890
Read 32 bytes from COM port: Arduino received integer = 890

enter an integer

I think i know the problem...

I start the java programm, i get the "enter an integer" message and then i open up the serial monitor on arduinoIDE... but it shows that it`s closed and i get this error: "Error opening serial port 'COM5'. (Port busy)"

This is the code in InteliiJ:

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import com.fazecast.jSerialComm.*;
import java.util.*;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        //Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        //primaryStage.setTitle("Hello World");
        //primaryStage.setScene(new Scene(root, 300, 275));
        //primaryStage.show();
        Scanner console = new Scanner(System.in);
        System.out.println("list COM ports ");
        SerialPort comPorts[] = SerialPort.getCommPorts();
        for (int i = 0; i < comPorts.length; i++)
            System.out.println(comPorts[i].getDescriptivePortName());
        int port = 2;
        comPorts[port].openPort();
        comPorts[port].setBaudRate(115200);
        try
        {
            while (true)
            {
                // transmit integer to serial port
                System.out.print("enter an integer ");
                int test = console.nextInt();                // read intger
                //System.out.println("you entered " + test);   // display it
                byte[] writeBuffer=(Integer.toString(test) + "\n").getBytes();
                comPorts[port].writeBytes(writeBuffer, writeBuffer.length);
            }
        } catch (Exception e) { e.printStackTrace(); }
        comPorts[1].closePort();
    }

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

When runned i get this:

list COM ports 
Standard Serial over Bluetooth link (COM3)
Standard Serial over Bluetooth link (COM4)
USB Serial Device (COM5) 
USBSER001
USBSER002
enter an integer

So comPorts[2] should be my Teensy, right?

And this is the code on the Teensy:

// SERIAL: read and echo integer value
void setup() {
  // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.setTimeout(60*60*1000ul);
}
void loop() {
//  Serial.print("enter integer ? ");
  int data=Serial.parseInt();
  Serial.print("Arduino received integer = ");
  Serial.println(data);
 }

your java code sends an integer to the arduino but does not read anything from the arduino
add code to read characters transmitted by the Arduino, e.g.

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import com.fazecast.jSerialComm.*;
import java.util.*;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        //Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        //primaryStage.setTitle("Hello World");
        //primaryStage.setScene(new Scene(root, 300, 275));
        //primaryStage.show();
        Scanner console = new Scanner(System.in);
        System.out.println("list COM ports ");
        SerialPort comPorts[] = SerialPort.getCommPorts();
        for (int i = 0; i < comPorts.length; i++)
            System.out.println(comPorts[i].getDescriptivePortName());
        int port = 2;
        comPorts[port].openPort();
        comPorts[port].setBaudRate(115200);
        try
        {
            while (true)
            {
                // transmit integer to serial port
                System.out.print("enter an integer ");
                int test = console.nextInt();                // read intger
                //System.out.println("you entered " + test);   // display it
                byte[] writeBuffer=(Integer.toString(test) + "\n").getBytes();
                comPorts[port].writeBytes(writeBuffer, writeBuffer.length);
      //  *** add code to receive data from arduino   *****
      while (comPorts[port].bytesAvailable() == 0)
         Thread.sleep(20);
      byte[] readBuffer = new byte[comPorts[port].bytesAvailable()];
      int numRead = comPorts[port].readBytes(readBuffer, readBuffer.length);
      System.out.print("Read " + numRead + " bytes from COM port: ");
       for (int i = 0; i < readBuffer.length; i++)   
           System.out.print((char)readBuffer[i]);
       System.out.println();
            }
        } catch (Exception e) { e.printStackTrace(); }
        comPorts[1].closePort();
    }

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

if I run with port=1

D:\temp2>java -cp D:\Programming\JAVA\JSerialComm\jSerialComm-1.3.11.jar;.  sample.Main
list COM ports
Communications Port (COM1)
USB-SERIAL CH340 (COM10)
enter an integer 78
Read 31 bytes from COM port: Arduino received integer = 78

enter an integer 66
Read 31 bytes from COM port: Arduino received integer = 66

enter an integer 77
Read 31 bytes from COM port: Arduino received integer = 77

enter an integer