java 实现串口通信
最近做了一个与硬件相关的项目,刚开始听说用java和硬件打交道,着实下了一大跳。java也可以操作硬件?
后来接触到是用java通过串口通信控制硬件感觉使用起来还不错,也很方便。
特拿出来和大家一起分享一下。
准备工作:
首先到SUN官网下载一个zip包:javacomm20-win32.zip
其中重要的有这几个文件:
win32com.dll
comm.jar
javax.comm.properties
按照说明配置好环境,如下:
将win32com.dll复制到bin目录下;将comm.jar复制到lib;把 javax.comm.properties也同样拷贝到lib目录下。然而在真正运行使用串口包的时候,仅作这些是不够的。因 为通常当运行“java MyApp”的时候,是由JRE下的虚拟机启动MyApp的。而我们只复制上述文件到JDK相应目录下,所以应用程序将会提示找不到串口。解决这个问题的 方法很简单,我们只须将上面提到的文件放到JRE相应的目录下就可以了
到这一个可以java 串口开发环境就搭建完成了
确认本机可以使用的串口:
- package test;
- import java.util.Enumeration;
- import java.util.HashMap;
- import javax.comm.CommPortIdentifier;
- import javax.comm.SerialPort;
- public class GetSerialPorts {
- public 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());
- }
- }
- }
- public static void main(String[] args) {
- GetSerialPorts GSP = new GetSerialPorts();
- GSP.listPortChoices();
- }
- }
复制代码
打开串口,关闭串口:
读数据:
- /**
- * TODO 接收端口數據
- *
- * @param InputStream
- * @return String
- * @throws
- */
- public String readData(InputStream is) {
- // 读取缓冲区域
- byte[] readBuffer = new byte[4096];
- int readDataLength = 0;
- try {
- readDataLength = is.read(readBuffer);
- // for (byte b : readBuffer) {
- // System.out.print(b);
- // }
- // System.out.println();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- return null;
- }
- // 将真实数据保存到零时数组中
- byte[] readTemp = new byte[readDataLength];
- for (int i = 0; i < readDataLength; i++) {
- readTemp[i] = readBuffer[i];
- }
- // 将byte数组转换为16进制字符串
- String stringTemp = FeelTheBase.bytesToHexString(readTemp);
- // System.out.println("指令返回值" + stringTemp);
- return stringTemp;
- }
复制代码
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持! |