jSerialComm: Java to arduino, not the same data.

Well Java consider Integer: a int in a Object like signed and byte (1 octet): a number between -127 and +127
C++ consider Integer: a signed int so 16 bit and a byte is a collection of bit like char or unsigned char.

I will try Ardulink Library to see if it's work. i need to install the library and the sketche on the arduino.
I'll open a new topic for that.

Hi

Swaggydogy:
Well Java consider Integer: a int in a Object like signed and byte (1 octet): a number between -127 and +127

Hum.. Java has a set of Primitive data types like byte, short, int, long, float, double, boolean and char. For those the byte count is known and and int is 4 bytes and Everything in Java binary format files is stored in big-endian order.

I would start there and explore what that means if I were you.

Also I want to add that after some text i have noted that the value that arduino echoe me back after java send the number is false.

I have consider that even if the number echo back is random, if it's between 0 and 10, then it should light the LED.

I see sometime if it echo the number 13 it light 2 LED, if it send 2 in doesn't light the LED number 2.
I have concluded that the arduino is not sending me back what he really received and it might a format of data between Java and C++ problem...

Swaggydogy:
I will try Ardulink Library to see if it's work. i need to install the library and the sketche on the arduino.
I'll open a new topic for that.

If that is for the purpose of exploring the same problem then keep the discussion in this Topic so we have all the info in the same place.

By the way I found where I had posted the JRuby code that works with the Arduino. See this Thread. The JRuby code is attached to Reply #2

...R

I think that’s the 3rd time I mention this

Have you written and tested a bare bone damn simple send a byte or an int and echo ?

Start there and Post that code

Here the arduino code

const int ref_pin = 2;


void setup() {

  for (int i = ref_pin; i < ref_pin + 10 ; i++)
  {
    pinMode(i,OUTPUT);
    digitalWrite(i,HIGH); // LED OFF
    delay(2);
  }
  
  Serial.begin(9600);
  while (!Serial) 
  {
    ; // wait for serial port to connect.
  }
}

void loop() {

  while (Serial.available() > 0) 
    {
        int byte_read = Serial.read();
        Serial.print(byte_read);
    }
}

Here the result:

Port is open
byte value = 2
DATA FROM ARDUINO: 1
Port is closed :slight_smile:

Swaggydogy:
Port is closed

I have asked you before --- why is the Java program closing the serial port?

...R

The java programm is closing the port after it send the data.

It say te port is closed with the smiley because i programm it for sending the data and close the port if the port has been closed correctly it print this message

Swaggydogy:
The java programm is closing the port after it send the data.

In that case I guess you missed Reply #5. Go back and study it.

...R

I will try to do the communication in C++ instead maybe it will work better

Swaggydogy:
I will try to do the communication in C++ instead maybe it will work better

If you have a choice of PC programming languages why not use Python. I have given you a link to a Python example in Reply #5.

...R

Well if i can use it like a command in my java programm.
Like the programm is mainly in Java but to communicate it use python?
Then i'll take it.

There is nothing wrong staying with java, what you want to do is fully achievable ... but if you open/close the serial port and reopen it your UNO will reboot

Swaggydogy:
Well if i can use it like a command in my java programm.
Like the programm is mainly in Java but to communicate it use python?

I had the impression you were thinking of giving up Java in favour of C++

If you want to continue with Java then what you want is definitely achievable entirely in Java - but I don't know the appropriate Java code.

Have you looked at the JRuby code in the link I gave you in Reply #23 - it may give you some ideas.

...R

Have you seen this example?

No you don't understand.
Communicate with Java to the Arduino start to making me lose my patience.
if the communicate work better in other language then i will make it like this:
The big part of the software is in Java but when i need to communicate, i will call with java the programm code in C++ or python to communicate with the Arduino.

One question thought, why you recommend mostly python to use Serial? and not C++ because it's more close to arduino?

Swaggydogy:
One question thought, why you recommend mostly python to use Serial? and not C++ because it's more close to arduino?

I recommended Python when I thought you were considering abandoning Java altogether. IMHO Python is much easier to program than C++. But I can't see any value in using Python alongside Java - or C++, for that matter.

Communicate with Java to the Arduino start to making me lose my patience.

It can be done and it can't be any more difficult with Java than with C++ or Python. Have you Googled for help with SERIAL as a Java problem rather than an Arduino problem?

Various suggestions have already been made in this Thread and you seem to have ignored them, or if you have tried them you have not told us how exactly you implemented the suggestion or given us details of the outcome.

...R

In java you only need to take care of endianness and ensuring you understand how many bytes are sent (or expected) for your given data type when communicating. There is no randomness to this.

Have you tried the example I pointed above ?

Hi i want to say that I finally communicate with the arduino.
I use the pySerial library to send data to the arduino and it work perectly
Then I execute the python programm in Java so i can now light LED.

Here the python code:

import sys, serial, time

if len(sys.argv) == 2:
    #print("le nombre que tu a mis est " + sys.argv[1])
    arduino = serial.Serial('/dev/cu.usbmodem1411', 9600, timeout=.1)
    print(arduino.name)

    if arduino.isOpen(): #on vérifie si le port a été ouvert
        time.sleep(1) # on met en pause le programme pendant 1 seconde pour laisser le temps à la connection entre l'ordi et le serial
        arduino.write(bytes(sys.argv[1],encoding='utf8') + "\n".encode('ascii')) #on envoie le message en byte en format utf8
        while True:
            try:
                
                data = arduino.readline() #on lit le retour de l'arduino
                if data:
                    print(data) #strip out the new lines for now
                    arduino.close() #on ferme le port
                    break #on quitte la boucle
            except Exception:
                print("Error: impossible d'ouvrir le port")
                break
    else:
        print("Le port est pas ouvert")


elif len(sys.argv) > 2:
    print("Erreur: Il y a trop d'arguments, 1 seul suffit")
    print("Veillez marquez la commande comme ceci: python Python_arduino.py [arg1]")



elif len(sys.argv) < 2:
    print("Erreur: Argument inexistant")
    print("Veillez marquez la commande comme ceci: python Python_arduino.py [arg1]")

The new java class Com_arduino that use the python programm to communicate with the arduino:

package server.arduino;
import java.io.*;


public class Com_arduino 
{
    private String[] cmd = new String[3]; 
    private int nbr_Led;
    private int ref_pin;

    public Com_arduino(int _nbr_Led, int _ref_pin) throws Exception
    {
        nbr_Led = _nbr_Led;
        ref_pin = _ref_pin;
        cmd[0] = "python3";
        cmd[1] = "arduino/Python_arduino.py";
        System.out.println("Arduino possédant: " + nbr_Led + " et commençant par la Led: " + ref_pin);
    }

    public void lightLed(int num_led) throws IOException
    {
        if (num_led >= 1 && num_led <= nbr_Led)
        {
            System.out.println("on allume la led: " + num_led);
            cmd[2] = Integer.toString(num_led);
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec(cmd);
        }
        else
        {
            System.out.println("Erreur: numéro de LED invalide");
        }
    }

    public void lightAllLed(String cmd_test) throws IOException
    {
        if (cmd_test.equals("test"))
        {
            cmd[2] = cmd_test;
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec(cmd);
        }
        else
        {
            System.out.println("Erreur: commande invalide");
        }
    }



}

The Serveur_trie to communicate to the arduino using the Com_arduino:

package server;

import cheque.Cheque;

import java.util.*;
import java.io.*;
import java.net.*; // permet de pouvoir faire du réseau avec java
import server.arduino.Com_arduino;

import com.fazecast.jSerialComm.*;


public class Serveur_trie extends Thread
{
    String name; // nom du client connecté au thread serveur
    Socket clientSocket;
    ObjectOutputStream out;
    private static HashMap<String, Serveur_trie> tableau_nom = new HashMap<String, Serveur_trie>(); // stocke les noms d'utilisateurs dans un tableau



    private int algorithme_trie(int num_donnee)
    {
        return num_donnee;
    }


    private void envoie_donnee_arduino(Integer num_led) throws Exception 
    {

        Com_arduino Arduino = new Com_arduino(10,2);
        Arduino.lightLed(num_led);


    }

    public void run() // fonction du thread
    {

        try (
			ObjectOutputStream out = new ObjectOutputStream(clientSocket.getOutputStream());
			ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream());
        )
        {
            while(true)
            {
                Object o = in.readObject();
                if (o instanceof Cheque)
                {
                    Cheque cheque = (Cheque) o;
                    System.out.println("info: " + cheque.get_Num_case());
                    envoie_donnee_arduino(algorithme_trie(cheque.get_Num_case()));
                }
            }
           /* else 
            if(o instanceof String) 
            {
                if( ((String) o).equals("BYE") )
                {
                    break;
                }
            }*/
        }
        catch (IOException e)
        {
            System.err.println("Exception while closing connection!");
        }
        catch (Exception e)
        {

        }

    }

    public Serveur_trie(Socket clientSocket)
    {
        this.clientSocket = clientSocket;
    }

    public static void main(String[] args) throws IOException, Exception /
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Bienvenue au serveur, Veillez saisir...");
        System.out.println("Votre numéro de port >"); 
        int num_port = scanner.nextInt(); 

        try (
        ServerSocket serverSocket = new ServerSocket(num_port); // on crée l'application serveur sur un port
        )
        {
            scanner.nextLine();
            Com_arduino test = new Com_arduino(10,2);
            System.out.println("Voulez vous tester les LED? taper la commande: test");
            String cmd = scanner.nextLine();
            test.lightAllLed(cmd);
            while (true)
            {
                Serveur_trie server = new Serveur_trie(serverSocket.accept()); 
                System.out.println("Client connecté");
                server.start();
            }
        }
        catch (IOException e)
        {
            System.err.println("Exception caught when trying to listen on port " + num_port);
            System.err.println(e.getMessage());
        }
        System.out.println("fermeture du serveur");
        scanner.close();

    }
}