Thank you guys for all your answers
I haven't solved my problem yet as I had another part to develop in my project.
Now, I'm back and I tried to send back the data received by arduino to java to show what it really receives.
I also added a sleep after serial.connect .
public static void main(String[] args) throws IOException, PortInUseException, NoSuchPortException{
SerialPortHandler serial = new SerialPortHandler();
serial.connect("COM2");
OutputStream serialOut = serial.getSerialOutputStream();
InputStream serialIn=serial.getSerialInputStream();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String s = "1";
byte[] b=new byte[5];
for (int i = 0 ; i<10; i++){
System.out.println("write " +i%2);
if(i%2==0)
serialOut.write(1);
else
serialOut.write(0);
serialOut.flush();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
serialIn.read(b);
System.out.print("Reçu ");
for (int j = 0; j < b.length; j++) {
System.out.print(b[j]+ " ");
}
System.out.println();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
serial.disconnect();
}
In my arduino code, I changed the control sequence and I used ascii code instead of the char itself :
int byteRead;
int led = 13 ;
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop() {
if (Serial.available()) {
delay(100);
while (Serial.available()){
byteRead = Serial.read();
switch(byteRead){
case 49:
digitalWrite(led, HIGH);
break;
case 0:
digitalWrite(led, LOW);
break;
default:
break;
}
Serial.write(byteRead);
}
}
delay(500);
}
That's what I receive in the java console :
write 0
Reçu 0 0 0 0 0
write 1
Reçu 0 0 0 0 0
write 0
Reçu 0 0 0 0 0
write 1
Reçu 0 0 0 0 0
and the led doesn't blink of course.
when I insert the serial.write into the case process :
case 49:
digitalWrite(led, HIGH);
serial.write(byteRead)
break;
the java program shows :
Reçu -32 1 1 1 1
I don't really know what does -32 stand for.