使用rxtxComm处理RS232 DB9中的握手线

时间:2012-04-21 06:18:03

标签: java rxtx handshake usbserial

我使用rxtxComm与Arduino(USB-Serial端口)进行通信(发送和接收数据)。如何使用rxtxComm库处理像DTR这样的握手线?你能给我一些关于这个或一些示例代码的教程???

  • 注意:我使用win7操作系统。我今天买了一个USB-Serial(DB9)适配器(21-4-2012);计划将LED阵列直接连接到rs232 ...

1 个答案:

答案 0 :(得分:0)

我猜你已安装了所有库。

更改为您的端口defaultPort =“COM24”;

尝试标准代码

package serialtest;

import java.util.*;
import gnu.io.*;
import java.io.IOException;
import java.io.OutputStream;


public class DXSimpleWrite {
    static Enumeration        portList;
    static CommPortIdentifier portId;
    static String         msgStr = "Hello, world!";
    static SerialPort         serialPort;
    static OutputStream       outputStream;
    static boolean        outputBufferEmptyFlag = false;

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

    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("SimpleWrite", 2000);
            } catch (PortInUseException e) {
            System.out.println("Port in use.");
            continue;
            } 

            try {
            outputStream = serialPort.getOutputStream();
            } catch (IOException e) {}

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

            try {
                serialPort.notifyOnOutputEmpty(true);
            } catch (Exception e) {
            System.out.println("Error setting event notification");
            System.out.println(e.toString());
            System.exit(-1);
            }

            System.out.println(
                "Writing "+msgStr+"\" to "+serialPort.getName());
            try {
            outputStream.write(msgStr.getBytes());
            } catch (IOException e) {}

            try {
               Thread.sleep(2000);  // Be sure data is xferred before closing
            } catch (Exception e) {}
            serialPort.close();
            System.exit(1);
        } 
        } 
    } 

    if (!portFound) {
        System.out.println("port " + defaultPort + " not found.");
    } 
    } 


}
祝你好运!