谁可以发给我个在windows下能用的JAVA串口通信啊~~要可以用的
解决方案 »
- 在非EDT线程访问同步方法里的Swing组件安全的不?
- List iterator迭代问题。
- 组件的问题~~
- 谁来帮我讲解一下这道题~~~谢谢
- (200分)HIBERNATE 问题,高手进
- 我刚接触JAVA两个月,现在开始想做个小项目,请高手推荐
- java.net.SocketException: Software caused connection abort: recv failed
- ant 使用中碰到的一些问题...大家喜欢 ant 还是 make ?
- 这小段代码哪里出问题了? 为什么它不会输出 e ?
- 想学JAVA,但不知从何入手
- java串口程序出了个错误,我不知道哪里有错?请高手指点下,谢谢~~
- 如何在当前程序中引入自己的包啊?
import java.io.*;
import java.util.*;
import javax.comm.*;
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
OutputStream outputStream;
SerialPort serialPort;
Thread readThread;
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType()==CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals( "COM1 ")) {
SimpleRead reader = new SimpleRead();
}
}
}
}
public SimpleRead() {
try {//打开串口COM1
serialPort = (SerialPort) portId.open( "SimpleReadApp ", 2000);
} catch (PortInUseException e) {}
try {//获得输入输出流
inputStream = serialPort.getInputStream();
outputStream = serialPort.getOutputStream();
} catch (IOException e) {}
try {//为串口添加监听器
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try {//配置串口
serialPort.setSerialPortParams(9600,//波特率9600bps
SerialPort.DATABITS_7,//7位数据位
SerialPort.STOPBITS_1,//1位停止位
SerialPort.PARITY_EVEN);//偶校验
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);//新建一线程
readThread.start();//启动线程
}
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {}
}
public void serialEvent(SerialPortEvent event) {
switch(event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE://如果有数据到达
byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0) {
//读取一个字节到readBuffer
int numBytes = inputStream.read(readBuffer);
}
System.out.print(new String(readBuffer));
} catch (IOException e) {}
break;
}
}
}
public static void main(String argv[]) {
new TestCom();
} public TestCom() {
CommPortIdentifier portId; Enumeration ports = CommPortIdentifier.getPortIdentifiers(); if (ports == null) {
System.out.println("No comm ports found!");
return;
} // print out all ports
System.out.println("printing all ports...");
while (ports.hasMoreElements()) {
System.out.println(" " + ((CommPortIdentifier) ports.nextElement()).getName()); }
}}