【发布时间】:2015-02-18 11:18:14
【问题描述】:
我正在尝试在 java 中执行 at 命令,我已经在 matlab 中完成了,但在 java 中我发现它有点困难。 是否有用于串行通信或命令的 java api? 我需要帮助来声明串行端口,然后向它发送命令。 我发现这个java代码打开了串口(com12),但它没有打开串口。
static Enumeration portList;
static CommPortIdentifier portId;
static String messageString = "at \n";
static SerialPort serialPort;
static OutputStream outputStream;
public static void main(String[] args) throws IOException {
// TODO code application logic here
portList = CommPortIdentifier.getPortIdentifiers();
System.out.println("trying");
while (portList.hasMoreElements()) {
System.out.println("trying");
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println("trying");
if (portId.getName().equals("COM12")) {
System.out.println("found");
try {
serialPort = (SerialPort)
portId.open("SimpleWriteApp", 2000);
} catch (PortInUseException e) {System.out.println("err");}
try {
outputStream = serialPort.getOutputStream();
} catch (IOException e) {System.out.println("err1");}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e)
{
System.out.println("err2");}
outputStream.write(messageString.getBytes());
System.out.println(messageString);
outputStream.close();
serialPort.close();
}
}
}
}
我使用的是电信设计调制解调器,我已经在 tera term 终端中执行了命令,所以我确信调制解调器或我发送命令的方式没有任何问题。我想我在打开串口和发送回车符方面很吃力。
提前致谢
【问题讨论】:
-
您的代码具体在哪里失败?您是否收到任何异常或错误消息?
标签: java at-command carriage-return serial-communication