Board Prototype

Attention : Programming, Development, Edtior check content blog in Main. Error be no Running.

Friday, October 10, 2025

[JAVA] Check Connect Serial Port Comm

 import com.fazecast.jSerialComm.SerialPort;

public class SerialExample {
    public static void main(String[] args) {
        SerialPort comPort = SerialPort.getCommPort("COM3"); // Change to your port
        comPort.setBaudRate(9600);

        if (comPort.openPort()) {
            System.out.println("Port opened successfully.");

            try {
                String message = "Hello Device\n";
                comPort.getOutputStream().write(message.getBytes());
                comPort.getOutputStream().flush();

                byte[] buffer = new byte[1024];
                int numRead = comPort.getInputStream().read(buffer);
                System.out.println("Received: " + new String(buffer, 0, numRead));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                comPort.closePort();
                System.out.println("Port closed.");
            }
        } else {
            System.out.println("Failed to open port.");
        }
    }

No comments: