在Java中与Arduino进行通信

时间:2012-08-14 16:26:21

标签: arduino communication

如何在Arduino Uno和Java应用之间进行通信?

我找到了 Arduino and Java ,但这对我来说并不清楚。

1 个答案:

答案 0 :(得分:0)

好的,我会修改相同的代码以帮助您理解。 (我将删除监听器并添加一个替换,这是不好的。你应该使用监听器)

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;

public class SerialTest implements SerialPortEventListener {

    SerialPort serialPort;
    private static final String PORT = "COM32";
    private InputStream input;
    private OutputStream output;
    private static final int TIME_OUT = 2000;
    private static final int DATA_RATE = 9600;

    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            if (currPortId.getName().equals(PORT)) {
                portId = currPortId;
                break;
            }
        }
        if (portId == null) {
            System.out.println("Could not find COM port.");
            return;
        }
        try {
            // open serial port, and use class name for the appName.
            serialPort = (SerialPort) portId.open(this.getClass().getName(),
                    TIME_OUT);

            // set port parameters
            serialPort.setSerialPortParams(DATA_RATE,
                    SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1,
                    SerialPort.PARITY_NONE);

            // open the streams
            input = serialPort.getInputStream();
            output = serialPort.getOutputStream();
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }

    /**
     * This should be called when you stop using the port.
     * This will prevent port locking on platforms like Linux.
     */
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    public static void main(String[] args) throws Exception {
        SerialTest main = new SerialTest();
        main.start();
    }

    public void start() throws IOException {
        initialize();
        System.out.println("Started");
        byte[] readBuffer = new byte[400];
        while (true) {
            int availableBytes = input.available();
            if (availableBytes > 0) {
                // Read the serial port
                input.read(readBuffer, 0, availableBytes);
                // Print it out
                System.out.print(new String(readBuffer, 0, availableBytes));
            }
        }
    }
}

运行此命令并将代码加载到写入串行的Arduino。然后程序将显示这些值。 (您可能需要相应地更改PORT)