有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Arduino Nano与Java应用程序的串行通信

我目前正在使用Arduino Nano为WS2812b LED(ARGB)构建一个控制器。我想在通过USB连接到Arduino的windows计算机上使用Java应用程序控制颜色。我编写此Java代码是为了向arduino发送基本数据:

public class Main {
    SerialPort sp;
    public Main() {
        openConnection("COM3");
        byte[] data =
                {0b00000001, 0b00000000, 0b01000000, 0b00000000, 0b01000000};
        try {
            sp.getOutputStream().write(data);
            sp.getOutputStream().flush();
            Thread.sleep(2000);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        closeConnection();
    } // End of constructor

    public static void main(String[] args) {
        new Main();
    } // End of main( String [] args )

    @Override
    public void actionPerformed(ActionEvent e) {
    } // End of actionPerformed( ActionEvent e )

    private void openConnection(String port) {
        if (port == null)
            throw new IllegalArgumentException("Port can't be null.");

        sp = SerialPort.getCommPort(port);
        sp.setComPortParameters(9600, 8, 1, 0);
        sp.setComPortTimeouts(SerialPort.TIMEOUT_WRITE_BLOCKING, 0, 0);

        if (sp.openPort())
            System.out.println("Port open.");
        else
            System.out.println("Port could not be opened.");
    } // End of openConnection( String port )

    private void closeConnection() {
        if (sp.closePort())
            System.out.println("Port closed.");
        else
            System.out.println("Port could not be closed.");
    } // End of closeConnection()
} // End of class

如果我运行这个程序,数据将被发送到Arduino(RX闪烁,奇怪的是L),但串行。available()始终返回0。以下是Arduino代码的相关部分:

void setup() {
    for (int i = 0; i < 8; i++) {
        ARGB[i].begin();
    }
    showAll();
    Serial.begin(9600);
}

//ARGB_X.setPixelColor(NUMBER_OF_LED, RED, GREEN, BLUE);
void loop() {
    if (Serial.available() > 0) {
        ARGB[0].setPixelColor(0, 10, 0, 0);
        ARGB[0].show();
    }
}

有人知道我做错了什么吗?如有任何建议,我们将不胜感激


共 (0) 个答案