23,125
社区成员
发帖
与我相关
我的任务
分享
package javaapplication1;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class TwoWaySerialComm {
public TwoWaySerialComm() {
super();
}
void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
if (commPort instanceof SerialPort) {
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
BufferedReader r = new BufferedReader(reader);
(new Thread(new SerialReader(r))).start();
} else {
System.out.println("Error: Only serial ports are handled by this example.");
}
}
}
/**
*
*/
//读的线程
public static class SerialReader implements Runnable {
BufferedReader in;
public SerialReader(BufferedReader in) {
this.in = in;
}
public void run() {
try {
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
*/
//写的线程
// public static class SerialWriter implements Runnable {
//
// OutputStream out;
//
// public SerialWriter(OutputStream out) {
// this.out = out;
// }
//
// public void run() {
// try {
// int c = 0;
// while ((c = System.in.read()) > -1) {
// this.out.write(c);
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
// }
public static void listPorts() {
@SuppressWarnings("unchecked")
java.util.Enumeration<CommPortIdentifier> portEnum = CommPortIdentifier.getPortIdentifiers();
int i = 1;
while (portEnum.hasMoreElements()) {
CommPortIdentifier portIdentifier = portEnum.nextElement();
System.out.println("第" + i + "个是 " + portIdentifier.getName() + " - " + getPortTypeName(portIdentifier.getPortType()));
}
}
static String getPortTypeName(int portType) {
switch (portType) {
case CommPortIdentifier.PORT_I2C:
return "I2C";
case CommPortIdentifier.PORT_PARALLEL:
return "Parallel";
case CommPortIdentifier.PORT_RAW:
return "Raw";
case CommPortIdentifier.PORT_RS485:
return "RS485";
case CommPortIdentifier.PORT_SERIAL:
return "Serial";
default:
return "unknown type";
}
}
}
listPorts(); //显示当前可用的串口号
try {
(new TwoWaySerialComm()).connect("/dev/ttyAMA0");
} catch (Exception e) {
e.printStackTrace();
}