Hello,
I am fairly new to using Arduino, I also don't really understand how the COM ports work yet. I am trying to send data from my PC (via Java) to my Arduino, and I saw tutorials on YouTube that it can be done with Serial communication.
Both my Java code and Arduino code are somewhat mixed together from several tutorials (I will paste the source code below). The Arduino code "listens" to incoming data via the Serial port COM3, and the Java code tries to open the same port in order to send data through it. In theory (or as I understood it), the Java program should be able to send data, even if the Arduino is currently "listening" on the Serial port. But if I start the Java program after plugging in the Arduino and recompiling my Arduino code, the port seems to get "blocked" by the Arduino, so the Java program cannot open the port anymore.
This is the Arduino code:
void setup() {
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect.
}
Serial.println("Init done");
}
void loop() {
if(Serial.available() > 0) {
byte incomingByte = 0;
incomingByte = Serial.read();
if (incomingByte != -1) {
delay(1000);
Serial.print("I got this ->");
Serial.print(incomingByte);
Serial.println("<-");
}
}
}
and this is the Java code: (using the library jSerialComm-2.7.0)
import com.fazecast.jSerialComm.SerialPort;
import java.io.IOException;
public class SendData {
public static void main(String[] args) {
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("Failed to open port :(");
return;
}
for (Integer i = 0; i < 5; ++i) {
try {
sp.getOutputStream().write(i.byteValue());
sp.getOutputStream().flush();
System.out.println("Sent number: " + i);
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (sp.closePort()) {
System.out.println("Port is closed :)");
} else {
System.out.println("Failed to close port :(");
return;
}
}
}
After running, the Java console outputs: "Failed to open port :("
My question is: How do I fix the code in order to make the communication work? Do I need to select some other port, include another library or try some completely different approach?
As I said, I'm really not experienced with Serial communication, so in my eyes, there could be a thousand reasons why this doesn't work, I just haven't found the right explanation online. If I left any crucial information out, let me know! I will gladly provide more information if necessary