I want to receive multiple bytes on an Arduino Uno from a Java program. The arduino deals with the data as soon as it's received, and thus I dont need to store it, I use the Serial RX buffer as temporary storage until I actually read the bytes. When fully implemented, about 150 bytes will be sent every time, but i've modified the buffer size to take care of that. I use jSerialComm as my serial library for java
I'v put some arduino and java code below. The arduino code works perfectly when I send the bytes from the IDE's serial monitor, lighting up the led as intended. But as soon as I try to send the bytes with the java code, the RX onboard led blinks, but the yellow led never lights up and ExecuteMove() doesn't trigger. I tried to put a Thread.sleep() before attempting to close the port, but that doesn't help.
Arduino
int GREEN = 4;
int BLUE = 3;
int YELLOW = 2;
void setup() {
pinMode(GREEN, OUTPUT);
pinMode(BLUE, OUTPUT);
pinMode(YELLOW, OUTPUT);
Serial.begin(9600);
}
void loop() {
byte rb = Serial.read();
if(rb != 255){ //Documentation says it sould be -1, but I'v tested it and
it's 255
digitalWrite(YELLOW, HIGH);
ExecuteMove(rb);
delay(500);
digitalWrite(YELLOW, LOW);
}
}
void ExecuteMove(byte _move){
Lights up the green LED if _move == 65, blue if 66 (Works perfectly)
}
Java
public static void main(String[] args) throws IOException,
InterruptedException{
SerialPort sp = SerialPort.getCommPort("COM3");
sp.setComPortParameters(9600, 8, 1, 0);
sp.setComPortTimeouts(SerialPort.TIMEOUT_WRITE_BLOCKING, 0, 0);
if(sp.openPort()) {
System.out.println("Port is open");
}else {
System.out.println("Port failed to open");
return;
}
byte[] message = {65, 66, 65};
for(int i = 0; i < message.length; i++) {
sp.getOutputStream().write(message[i]); //Sends the message
sp.getOutputStream().flush();
}
if(sp.closePort()) {
System.out.println("Port is closed");
}else {
System.out.println("Failed to close port");
return;
}
}
As I already stated, the arduino code alone works perfectly with the monitor, but when I use the java code to send bytes, only the RX led lights up, but none of "my" LEDs do
if(rb != 255){ //Documentation says it sould be -1, but I'v tested it and it's 255- the return value isint, notbyte