package Cilent;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TooManyListenersException;
import javax.print.attribute.standard.PrinterMessageFromOperator;
public class SendTest implements SerialPortEventListener{
protected static CommPortIdentifier portid = null; //通讯端口标识符
protected static SerialPort comPort = null; //串行端口
protected int BAUD = 9600; //波特率
protected int DATABITS = SerialPort.DATABITS_8;; //数据位
protected int STOPBITS = SerialPort.STOPBITS_1; //停止位
protected int PARITY = SerialPort.PARITY_NONE; //奇偶检验
private static OutputStream outputStream; //输出流
private static InputStream inputStream; //输入流
private static byte[] readBuffer = new byte[1024]; // 4k的buffer空间,缓存串口读入的数据
StringBuilder buf = new StringBuilder(128);
public static void main(String[] args) {
SendTest my = new SendTest();
my.setSerialPortNumber();
sendMsg();
}
//读取所有串口
private void listPortChoices() {
CommPortIdentifier portId;
Enumeration en = CommPortIdentifier.getPortIdentifiers();
// iterate through the ports.
while (en.hasMoreElements()) {
portId = (CommPortIdentifier) en.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println(portId.getName());
}
}
}
//设置串口号
private void setSerialPortNumber() {
String osName = null;
String osname = System.getProperty("os.name", "").toLowerCase();
if (osname.startsWith("windows")) {
// windows
osName = "COM1";
}
System.out.println(osName);
try {
portid = CommPortIdentifier.getPortIdentifier(osName);
// portid = CommPortIdentifier.getPortIdentifier(Port);
if(portid.isCurrentlyOwned()){
System.out.println("端口在使用");
}else{
comPort = (SerialPort) portid.open(this.getClass().getName(), 1000);
}
} catch (PortInUseException e) {
System.out.println("端口被占用");
e.printStackTrace();
} catch (NoSuchPortException e) {
System.out.println("端口不存在");
e.printStackTrace();
}
try {
inputStream = comPort.getInputStream(); //从COM1获取数据
outputStream = comPort.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
comPort.addEventListener(this); //给当前串口增加一个监听器
comPort.notifyOnDataAvailable(true); //当有数据是通知
} catch (TooManyListenersException e) {
e.printStackTrace();
}
try {
//设置串口参数依次为(波特率,数据位,停止位,奇偶检验)
comPort.setSerialPortParams(this.BAUD, this.DATABITS, this.STOPBITS, this.PARITY);
} catch (UnsupportedCommOperationException e) {
System.out.println("端口操作命令不支持");
e.printStackTrace();
}
}
//将输入的16进制string转成字节
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
//向串口发送信息方法
public static void sendMsg(){
String msg="71340001";//要发送的命令msg
try {
outputStream.write(hexStringToBytes(msg));
} catch (IOException e) {
e.printStackTrace();
}
}
//字节转换成十六进制字符串
public static String bytesToHexString(byte[] src){
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
@Override
public void serialEvent(SerialPortEvent event) {
switch (event.getEventType()) {
case SerialPortEvent.BI://Break interrupt,通讯中断
case SerialPortEvent.OE://Overrun error,溢位错误
case SerialPortEvent.FE://Framing error,传帧错误
case SerialPortEvent.PE://Parity error,校验错误
case SerialPortEvent.CD://Carrier detect,载波检测
case SerialPortEvent.CTS://Clear to send,清除发送
case SerialPortEvent.DSR://Data set ready,数据设备就绪
case SerialPortEvent.RI://Ring indicator,响铃指示
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:// 当有可用数据时读取数据,并且给串口返回数据
try
{
// 多次读取,将所有数据读入
while (inputStream.available() > 0) {
System.out.println("接收数据:"+((byte) inputStream.read()));
}
}
catch ( IOException e )
{
e.printStackTrace();
}
break;
}
}
}
各位大神,现在做的项目是往cpld发送指令控制,发送16进制的指令需要接收cpld返回的16进制数据判断指令是否正确执行,这是按照网上的例子写的,现在解决了发送指令,但是接收部分不知道如何接收16进制的返回数据,用串口调试助手往com1发送16进制数据只能显示2位的10进制,请问如何将接收的16进制数据正确显示出来,新手实在没办法了