Board Prototype

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

Friday, October 10, 2025

[Java Programming] Port Hardware

 import gnu.io.*;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;

public class SerialComm {
    public static void main(String[] args) {
        try {
            Enumeration<?> portList = CommPortIdentifier.getPortIdentifiers();

            while (portList.hasMoreElements()) {
                CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();

                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL &&
                    portId.getName().equals("COM3")) { // Change to your port

                    SerialPort serialPort = (SerialPort) portId.open("SerialComm", 2000);
                    InputStream inputStream = serialPort.getInputStream();
                    OutputStream outputStream = serialPort.getOutputStream();

                    serialPort.setSerialPortParams(9600,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);

                    outputStream.write("Hello Device\n".getBytes());

                    byte[] buffer = new byte[1024];
                    int len = inputStream.read(buffer);
                    System.out.println("Received: " + new String(buffer, 0, len));

                    serialPort.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

No comments: