有 Java 编程相关的问题?

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

关于使用java rxtx控制led的串口

我写了一个简单的led控制程序并上传到Arduino,当我使用“串行监视器”向Arduino发送控制命令时,它工作得很好。同时,我尝试在ubuntu上编写一个java程序来发送命令。当我运行java程序时,我可以看到RX指示灯闪烁,但Arduino似乎无法识别这些命令

我把代码贴在这里。希望有人能帮助我

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

import gnu.io.* ;     // rxtx serial port driver

public class SerialTest {
    static Enumeration          portList;
    static CommPortIdentifier   portId;
    static SerialPort           serialPort;
    static OutputStream         outputStream;
    static boolean              outputBufferEmptyFlag = false;

    public static void main( String[] args) {
        boolean portFound = false;
        String  defaultPort = "/dev/ttyACM0";

        if (args.length > 0) {
            defaultPort = args[0];
        }

        portList = CommPortIdentifier.getPortIdentifiers();

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

            if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

                if(portId.getName().equals(defaultPort)) {
                    System.out.println("Found port " + defaultPort);

                    portFound = true;

                    try {
                        serialPort = (SerialPort) portId.open("SerialTest", 2000);
                    } catch (PortInUseException e) {
                        System.out.println("Port in use.");
                        continue;
                    } 

                    try {
                        serialPort.setSerialPortParams(9600, 
                                        SerialPort.DATABITS_8, 
                                        SerialPort.STOPBITS_1, 
                                        SerialPort.PARITY_NONE);
                    } catch (UnsupportedCommOperationException e) {}

                    try {
                        outputStream = serialPort.getOutputStream();
                        outputStream.write("cccc".getBytes());
                    } catch (IOException e) {}

                    serialPort.close();
                    System.exit(1);
                } 
            } 
        }
    }
}

共 (0) 个答案