Java " />

扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

java浠g爜鎬庝箞璺烲ORA鍩虹珯杩炴帴

扬州沐宇科技
2024-05-28 16:36:19
Java

鍦↗ava涓繛鎺ュ埌LORA鍩虹珯鍙互閫氳繃浣跨敤鐩稿簲鐨凩ORA妯″潡杩涜閫氫俊銆備互涓嬫槸涓€涓ず渚嬩唬鐮侊紝灞曠ず濡備綍鍦↗ava涓娇鐢⊿erialPort杩涜涓插彛閫氫俊鏉ヨ繛鎺ュ埌LORA鍩虹珯锛?/p>

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

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

public class LoRaConnection {

    private static final int TIMEOUT = 2000;
    private static final int BAUD_RATE = 9600;

    private SerialPort serialPort;
    private InputStream input;
    private OutputStream output;

    public void connect(String portName) {
        CommPortIdentifier portIdentifier;
        try {
            portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
            if (portIdentifier.isCurrentlyOwned()) {
                System.out.println("Error: Port is currently in use");
            } else {
                serialPort = (SerialPort) portIdentifier.open(this.getClass().getName(), TIMEOUT);
                serialPort.setSerialPortParams(BAUD_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                input = serialPort.getInputStream();
                output = serialPort.getOutputStream();

                System.out.println("Connected to LoRa module on port: " + portName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void disconnect() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
            System.out.println("Disconnected from LoRa module");
        }
    }

    public void sendData(byte[] data) {
        try {
            output.write(data);
            output.flush();
            System.out.println("Data sent successfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public byte[] receiveData() {
        byte[] buffer = new byte[1024];
        int len = -1;
        try {
            len = input.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] data = new byte[len];
        System.arraycopy(buffer, 0, data, 0, len);
        System.out.println("Received data: " + new String(data));
        return data;
    }

    public static void main(String[] args) {
        LoRaConnection connection = new LoRaConnection();
        connection.connect("/dev/ttyUSB0"); // Replace with the actual port name of your LORA module
        connection.sendData("Hello LORA".getBytes());
        connection.receiveData();
        connection.disconnect();
    }
}

鍦ㄨ繖涓ず渚嬩唬鐮佷腑锛屾垜浠娇鐢ㄤ簡RXTXcomm搴撴潵鎿嶄綔涓插彛锛屼綘闇€瑕佷笅杞藉苟瀵煎叆璇ュ簱銆傚湪connect()鏂规硶涓紝鎴戜滑鎵撳紑鎸囧畾鐨勪覆鍙e苟璁剧疆閫氫俊鍙傛暟銆傜劧鍚庡彲浠ヤ娇鐢?code>sendData()鏂规硶鍙戦€佹暟鎹紝浣跨敤receiveData()鏂规硶鎺ユ敹鏁版嵁銆傛渶鍚庯紝閫氳繃disconnect()鏂规硶鍏抽棴涓插彛杩炴帴銆?/p>

璇锋敞鎰忥紝浣犻渶瑕佹牴鎹綘鐨凩ORA妯″潡鐨勫叿浣撳瀷鍙峰拰閫氫俊鍗忚杩涜鐩稿簲鐨勮皟鏁淬€?/p>

扫码添加客服微信