Hello everyone ,
i am working on a project in internship and i have some issues for trying to cummunicate a Java Programme to a Arduino Mega 2560 while using the librairie jSerialComm. I use the usb cable to connect the arduino.
Here the things, I send the data to the card by the port: /dev/cu.usbmodem1411, but everytime i send a number (for example: 1) in the arduino it's never the same number. The goal of sending data to the arduino is for typing a led number in java to make it light in arduino with of course Serial. I want also to send word to the arduino.
If i send 1, it will light the led number one.
If i type "test", il will light all the led.
For any member of this forum who have worked with jSerialcomm or any other java library better then RxTx to communicate with the arduino. how do you send the same data to your arduino? why it work with the Serial monitor but not with my java programm? what does the Serial monitor really send to the arduino?
I have already checked a lot of topic but none of them work for me...
My project is divided in two parts: Java part using Sockets and Arduino part...
I communicate with the Serveur_trie.java file to the arduino
The Server java file:
package server;
import cheque.Cheque;
import java.util.*;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.net.*;
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) // permet de trouver la case pour trier le cheque
{
return num_donnee;
}
private void display_port()
{
SerialPort[] ports = SerialPort.getCommPorts();
for (int i = 0; i < ports.length; i++)
{
System.out.println(ports[i].getSystemPortName());
}
}
private void envoie_donnee_arduino(Integer num_led) throws Exception
// permet d'envoyer les données de l'algorithme à la partie Arduino13
{
display_port();
SerialPort sp = SerialPort.getCommPort("/dev/cu.usbmodem1411"); // port arduino Mega 2650
System.out.println(sp.getDescriptivePortName());
sp.setComPortParameters(9600, 8, 1, 0); // default connection settings for Arduino
sp.setComPortTimeouts(SerialPort.TIMEOUT_WRITE_BLOCKING, 0, 0); // block until bytes can be written
if (sp.openPort())
{
System.out.println("Port is open");
}
else
{
System.out.println("Failed to open port");
return;
}
sp.addDataListener(new SerialPortDataListener()
{
@Override
public int getListeningEvents() {
return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
}
@Override
public void serialEvent(SerialPortEvent event) {
if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE) {
return;
}
byte[] newData = new byte[sp.bytesAvailable()];
int numRead = sp.readBytes(newData, newData.length);
System.out.println("Read " + numRead + " bytes. " + newData[0]);
}
});
Thread.sleep(2000);
byte[] writeBuffer = Integer.toString(num_led).getBytes(StandardCharsets.UTF_8);
//char test = Character.forDigit(num_led, 10);
System.out.println("byte value = " + writeBuffer[0]);
sp.getOutputStream().write(num_led); // écrit les données en BYTE du serveur vers le port
sp.getOutputStream().flush();
if (sp.closePort())
{
System.out.println("Port is closed :)");
}
else
{
System.out.println("Failed to close port :(");
return;
}
}
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
{
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(); // on enregistre le numéro du
try (
ServerSocket serverSocket = new ServerSocket(num_port);
)
{
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();
}
}
The arduino file:
#include <Wire.h>
#include <stdio.h>
const int ref_pin = 2;
const int LIM_TAB = 5;
char tab_carac[LIM_TAB];
boolean newData = false;
void all_led(int dep_led)
{
for (int i = 0 ; i <= 4 ; i++)
{
for (int i = ref_pin; i < ref_pin + 10 ; i++)
{
digitalWrite(i,LOW);
}
delay(1000);
for (int i = ref_pin; i < ref_pin + 10 ; i++)
{
digitalWrite(i,HIGH);
}
delay(1000);
}
}
boolean is_a_number(int n)
{
return n >= 48 && n <= 57;
}
int ascii2int(int n, int byte_read)
{
return n*10 + (byte_read - 48);
}
/*int concat(int a, int b)
{
char s1[20];
char s2[20];
// Convert both the integers to string
sprintf(s1, "%d", a);
sprintf(s2, "%d", b);
// Concatenate both strings
strcat(s1, s2);
// Convert the concatenated string
// to integer
int c = atoi(s1);
// return the formed integer
return c;
}*/
boolean is_test(char tab[])
{
if (strncmp(tab,"test",4) == 0)
{
return true;
}
else
{
return false;
}
}
//-------------------------------------------------------------------
void setup()
{
// put your setup code here, to run once:
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.
}
Serial.print("Pin ready!");
}
void loop()
{
collectDataFromJava();
DataLightLED();
memset(tab_carac,0,sizeof(tab_carac));
newData = false;
}
void collectDataFromJava()
{
int ndx = 0;
while (newData == false)
{
while (Serial.available() > 0)
{
byte byte_read = Serial.read();
if (byte_read != '\n')
{
tab_carac[ndx] = byte_read;
ndx++;
}
else
{
tab_carac[ndx] = '\0';
ndx = 0;
newData = true;
}
}
}
}
void DataLightLED()
{
if (tab_carac[0] != '\0')
{
if(is_test(tab_carac) == true)
{
all_led(ref_pin);
}
else
{
int pin_a_allumer = 0;
for (int b = 0; b < sizeof(tab_carac) ; b++)
{
if (is_a_number(tab_carac[b]))
{
pin_a_allumer = 10*(pin_a_allumer) + (ascii2int(0,tab_carac[b]));
}
}
digitalWrite(pin_a_allumer + 1,LOW); // LED OFF
}
}
}
Thanks in advance for your response.