Java中操作串口的步骤与实现
Java中操作串口的步骤与实现
设置串口API:
1 解压缩javacomm20-win32,
把omm.jar
放入 Java-home\jre\lib\ext 目录内
Java-home\jre\lib
Java-home\lib
把 javax.comm.properties文件
放入 Java-home\jre\lib\ext 目录内
Java-home\jre\lib
Java-home\lib
2 win32com.dll 文件放入:
a) java-home\bin
b) java-home\jre\bin
枚举计算机串口代码:
import java.util.Enumeration;
import javax.comm.*;
public class comtest
{
static Enumeration en = CommPortIdentifier.getPortIdentifiers();
static CommPortIdentifier portId;
public static void main(String[] args)
{
while (en.hasMoreElements())
{
portId = (CommPortIdentifier) en.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
System.out.println(portId.getName());
}
}
}
}
实现串口方式与RFID设备通信,并获得版本号
import java.util.Enumeration;
import javax.comm.*;
import java.io.*;
public class comgetver
{
static Enumeration portList;
static CommPortIdentifier portId;
static SerialPort serialPort;
static OutputStream outputStream;
static InputStream inputStream;
public static void main(String[] args)
{
byte[] RecData= new byte[256];
byte[] getversion= new byte[4]; //获得读写器版本号命令
/*组命令包:40 02 02 bc :读版本号命令*/
getversion[0]=(byte)(0x40);
getversion[1]=(byte)(0x02);
getversion[2]=(byte)(0x02);
getversion[3]=(byte)(0xbc);
try
{
CommPortIdentifier commportidentifier = CommPortIdentifier.getPortIdentifier("COM1");
serialPort = (SerialPort)commportidentifier.open("smsapp", 3000);
outputStream = serialPort.getOutputStream();
inputStream = serialPort.getInputStream();
serialPort.setSerialPortParams(57600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
推荐文章 |
