SpringBoot+jSerialComm实现Java串口通信 读取串口数据以及发送数据

这篇具有很好参考价值的文章主要介绍了SpringBoot+jSerialComm实现Java串口通信 读取串口数据以及发送数据。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

记录一下使用SpringBoot+jSerialComm实现Java串口通信,使用Java语言开发串口,对串口进行读写操作,在win和linux系统都是可以的,有一点好处是不需要导入额外的文件。

案例demo源码:SpringBoot+jSerialComm实现Java串口通信 读取串口数据以及发送数据

之前使用RXTXcomm实现Java串口通信,这种方式对linux(centos)的支持效果不好还有些问题 但在win下面使用还不错,原文地址:SpringBoot+RXTXcomm实现Java串口通信 读取串口数据以及发送数据

不需要额外导入文件 比如dll 只需要导入对应的包

 <dependency>
     <groupId>com.fazecast</groupId>
     <artifactId>jSerialComm</artifactId>
     <version>2.9.2</version>
 </dependency>

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <groupId>boot.example.jSerialComm</groupId>
    <artifactId>boot-example-jSerialComm-2.0.5</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>boot-example-jSerialComm-2.0.5</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fazecast</groupId>
            <artifactId>jSerialComm</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.2</version>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <mainClass>boot.example.SerialPortApplication</mainClass>
                    <includeSystemScope>true</includeSystemScope><!--外部进行打包-->
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

SerialPortApplication启动类

package boot.example;


import boot.example.serialport.SerialPortManager;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import javax.annotation.PreDestroy;
import java.io.IOException;

/**
 *  蚂蚁舞
 */
@SpringBootApplication
@EnableScheduling
@EnableAsync
public class SerialPortApplication implements CommandLineRunner {

    public static void main(String[] args) throws IOException {
        SpringApplication.run(SerialPortApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        try{
            //  win
            SerialPortManager.connectSerialPort("COM1");
            //  linux centos
            //SerialPortManager.connectSerialPort("ttyS1");
        } catch (Exception e){
            System.out.println(e.toString());
        }

    }

    @PreDestroy
    public void destroy() {
        SerialPortManager.closeSerialPort();
    }


}

SwaggerConfig

package boot.example;

import com.google.common.base.Predicates;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 *  蚂蚁舞
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
                .apis(RequestHandlerSelectors.any()).paths(PathSelectors.any())
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .paths(PathSelectors.regex("/.*"))
                .build().apiInfo(apiInfo());
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("SpringBoot+jSerialComm实现Java串口通信 读取串口数据以及发送数据")
                .description("测试接口")
                .version("0.01")
                .build();
    }

}

SerialPortController

package boot.example.controller;

import boot.example.serialport.ConvertHexStrAndStrUtils;
import boot.example.serialport.SerialPortManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 *  蚂蚁舞
 */
@Controller
@RequestMapping("/serialPort")
public class SerialPortController {

    @GetMapping("/list")
    @ResponseBody
    public List<String> listPorts() {
        List<String> portList = SerialPortManager.getSerialPortList();
        if(!portList.isEmpty()){
            return portList;
        }
        return null;
    }


    @PostMapping("/send/{hexData}")
    @ResponseBody
    public String sendPorts(@PathVariable("hexData") String hexData) {
        if (SerialPortManager.SERIAL_PORT_STATE){
            SerialPortManager.sendSerialPortData(ConvertHexStrAndStrUtils.hexStrToBytes(hexData));
            return "success";
        }
        return "fail";
    }



}

ConvertHexStrAndStrUtils

package boot.example.serialport;


import java.nio.charset.StandardCharsets;

/**
 *  蚂蚁舞
 */
public class ConvertHexStrAndStrUtils {

    private static final char[] HEXES = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String bytesToHexStr(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        StringBuilder hex = new StringBuilder(bytes.length * 2);
        for (byte b : bytes) {
            hex.append(HEXES[(b >> 4) & 0x0F]);
            hex.append(HEXES[b & 0x0F]);
        }
        return hex.toString().toUpperCase();
    }

    public static byte[] hexStrToBytes(String hex) {
        if (hex == null || hex.length() == 0) {
            return null;
        }
        char[] hexChars = hex.toCharArray();
        byte[] bytes = new byte[hexChars.length / 2];   // 如果 hex 中的字符不是偶数个, 则忽略最后一个
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt("" + hexChars[i * 2] + hexChars[i * 2 + 1], 16);
        }
        return bytes;
    }

    public static String strToHexStr(String str) {
        StringBuilder sb = new StringBuilder();
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(HEXES[bit]);
            bit = bs[i] & 0x0f;
            sb.append(HEXES[bit]);
        }
        return sb.toString().trim();
    }

    public static String hexStrToStr(String hexStr) {
        //能被16整除,肯定可以被2整除
        byte[] array = new byte[hexStr.length() / 2];
        try {
            for (int i = 0; i < array.length; i++) {
                array[i] = (byte) (0xff & Integer.parseInt(hexStr.substring(i * 2, i * 2 + 2), 16));
            }
            hexStr = new String(array, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        return hexStr;
    }

}



SerialPortManager

package boot.example.serialport;

import com.fazecast.jSerialComm.SerialPort;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 *  蚂蚁舞
 */
public class SerialPortManager {

    public static final int SERIAL_BAUD_RATE = 115200;

    public static volatile boolean SERIAL_PORT_STATE = false;

    public static volatile SerialPort SERIAL_PORT_OBJECT = null;

    //查找所有可用端口
    public static List<String> getSerialPortList() {
        // 获得当前所有可用串口
        SerialPort[] serialPorts = SerialPort.getCommPorts();
        List<String> portNameList = new ArrayList<String>();
        // 将可用串口名添加到List并返回该List
        for(SerialPort serialPort:serialPorts) {
            System.out.println(serialPort.getSystemPortName());
            portNameList.add(serialPort.getSystemPortName());
        }
        //去重
        portNameList = portNameList.stream().distinct().collect(Collectors.toList());
        return portNameList;
    }

    //  连接串口
    public static void connectSerialPort(String portName){
        try {
            SerialPort serialPort = SerialPortManager.openSerialPort(portName, SERIAL_BAUD_RATE);
            TimeUnit.MILLISECONDS.sleep(2000);
            //给当前串口对象设置监听器
            serialPort.addDataListener(new SerialPortListener(new SerialPortCallback()));
            if(serialPort.isOpen()) {
                SERIAL_PORT_OBJECT = serialPort;
                SERIAL_PORT_STATE = true;
                System.out.println(portName+"-- start success");
            }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }


    //  打开串口
    public static SerialPort openSerialPort(String portName, Integer baudRate) {
        SerialPort serialPort = SerialPort.getCommPort(portName);
        if (baudRate != null) {
            serialPort.setBaudRate(baudRate);
        }
        if (!serialPort.isOpen()) {  //开启串口
            serialPort.openPort(1000);
        }else{
            return serialPort;
        }
        serialPort.setFlowControl(SerialPort.FLOW_CONTROL_DISABLED);
        serialPort.setComPortParameters(baudRate, 8, SerialPort.ONE_STOP_BIT, SerialPort.NO_PARITY);
        serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_BLOCKING | SerialPort.TIMEOUT_WRITE_BLOCKING, 1000, 1000);
        return serialPort;
    }

    //  关闭串口
    public static void closeSerialPort() {
        if (SERIAL_PORT_OBJECT != null && SERIAL_PORT_OBJECT.isOpen()){
            SERIAL_PORT_OBJECT.closePort();
            SERIAL_PORT_STATE = false;
            SERIAL_PORT_OBJECT = null;
        }
    }

    //  发送字节数组
    public static void sendSerialPortData(byte[] content) {
        if (SERIAL_PORT_OBJECT != null && SERIAL_PORT_OBJECT.isOpen()){
            SERIAL_PORT_OBJECT.writeBytes(content, content.length);
        }
    }

    //  读取字节数组
    public static byte[] readSerialPortData() {
        if (SERIAL_PORT_OBJECT != null && SERIAL_PORT_OBJECT.isOpen()){
            byte[] reslutData = null;
            try {
                if (!SERIAL_PORT_OBJECT.isOpen()){return null;};
                int i=0;
                while (SERIAL_PORT_OBJECT.bytesAvailable() > 0 && i++ < 5) Thread.sleep(20);
                byte[] readBuffer = new byte[SERIAL_PORT_OBJECT.bytesAvailable()];
                int numRead = SERIAL_PORT_OBJECT.readBytes(readBuffer, readBuffer.length);
                if (numRead > 0) {
                    reslutData = readBuffer;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return reslutData;
        }
        return null;
    }



}

SerialPortListener

package boot.example.serialport;


import com.fazecast.jSerialComm.SerialPort;
import com.fazecast.jSerialComm.SerialPortDataListener;
import com.fazecast.jSerialComm.SerialPortEvent;

/**
 *  蚂蚁舞
 */
public class SerialPortListener implements SerialPortDataListener {

    private final SerialPortCallback serialPortCallback;

    public SerialPortListener(SerialPortCallback serialPortCallback) {
        this.serialPortCallback = serialPortCallback;
    }

    @Override
    public int getListeningEvents() { //必须是return这个才会开启串口工具的监听
        return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;
    }

    @Override
    public void serialEvent(SerialPortEvent serialPortEvent) {
        if (serialPortCallback != null) {
            serialPortCallback.dataAvailable();
        }
    }
}


SerialPortCallback

package boot.example.serialport;


import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  蚂蚁舞
 */
public class SerialPortCallback {

    public void dataAvailable() {
        try {
            //当前监听器监听到的串口返回数据 back
            byte[] back = SerialPortManager.readSerialPortData();
            System.out.println("back-"+(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))+"--"+ConvertHexStrAndStrUtils.bytesToHexStr(back));
            String s = ConvertHexStrAndStrUtils.bytesToHexStr(back);
            System.out.println("rev--data:"+s);
            //throw new Exception();
        } catch (Exception e) {
            System.out.println(e.toString());
        }
    }
}

项目结构
java向串口发送数据,SpringBoot+Demo,SpringBoot读取串口,SpringBoot串口通信,Java串口通讯,Java串口通信,Java实现串口通信

demo使用的波特率是115200 其他参数就默认的就好,一般只有波特率改动

启动项目和启动com工具(项目和com之间使用的是com1和com2虚拟串口 虚拟串口有工具的,比如Configure Virtual Serial Port Driver)
java向串口发送数据,SpringBoot+Demo,SpringBoot读取串口,SpringBoot串口通信,Java串口通讯,Java串口通信,Java实现串口通信
可以看到com1和com2都已经在使用 应用程序用的com1端口 com工具用的com2端口,这样的虚拟串口工具可以模拟调试使用的 应用程序通过com1向com2发送数据 ,com工具通过com2向com1的应用程序发送数据,全双工双向的,如此可以测试了。

访问地址

http://localhost:24810/doc.html

查看当前的串口 win系统下的两个虚拟串口
java向串口发送数据,SpringBoot+Demo,SpringBoot读取串口,SpringBoot串口通信,Java串口通讯,Java串口通信,Java实现串口通信
通过虚拟串口发送数据到com工具
java向串口发送数据,SpringBoot+Demo,SpringBoot读取串口,SpringBoot串口通信,Java串口通讯,Java串口通信,Java实现串口通信
通过com工具查看收到的数据已经发送数据给应用程序
java向串口发送数据,SpringBoot+Demo,SpringBoot读取串口,SpringBoot串口通信,Java串口通讯,Java串口通信,Java实现串口通信
控制台收到数据
java向串口发送数据,SpringBoot+Demo,SpringBoot读取串口,SpringBoot串口通信,Java串口通讯,Java串口通信,Java实现串口通信
记录着,将来用得着。文章来源地址https://www.toymoban.com/news/detail-754465.html

到了这里,关于SpringBoot+jSerialComm实现Java串口通信 读取串口数据以及发送数据的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【STM32】STM32F103C8T6串口通信,实现3个串口收发数据

    串口通信(Serial Communications)实现单片机与电脑或者其它外设进行通信,通信时只需两根线(TX,RX)就可以实现数据传输。STM32f103有三个串口,分别为串口1(RX PA10, TX PA 9),串口2(RX PA3,TX PA2),串口3(RX PB11,TX PB10)。 以下代码是配置三个串口: usart.c usart.h main.c 注意,

    2024年02月12日
    浏览(36)
  • SpringBoot(java)实现websocket实现实时通信

    WebSockets是一种在Web应用程序中实现实时通信的技术。它允许客户端和服务器之间建立持久的、双向的通信通道,从而使得服务器可以实时向客户端推送数据,而不需要客户端不断地向服务器发起请求。这种实时通信的能力对于需要即时更新数据的应用程序非常有用,比如在线

    2024年04月29日
    浏览(32)
  • 关于Qt用多线程实现usb温度传感器(串口通信)的数据接收中遇到的问题及猜想(不一定正确)

    由于是初学,仅仅对串口编程有个了解,大概的功能是通过两个按钮实现串口数据的接收和暂停,其他的功能暂不深入研究。 通过串口调试助手发现,该串口的属性设置如左所示,接收的数据转为字符串后显示格式如右所示。这里是打算将右边的温度显示在一个LCD控件中,效

    2024年02月01日
    浏览(29)
  • 采用串口中断方式实现串口通信

    中断方式 中断方式是处理器和外部设备的数据传输方式。一方通过申请中断的方式与另一方进行数据传输,收发双方可以并行工作。 中断系统 中断装置和中断处理程序统称为中断系统。 中断系统是计算机的重要组成部分。实时控制、故障自动处理、计算机与外围设备间的数

    2024年02月16日
    浏览(25)
  • Java 串口通信(RS232/485)

    Java 实现串口通信,同时通过 WebSocket 与 UI 实时交互传递通信数据 准备工作: 虚拟串口工具:Launch Virtual Serial Port Driver 串口调试助手:SSCOM RS485 在线 CRC检验码计算:CRC 测试链接 1.扩展包和依赖库 以上两个包可以直接网上下载,注意和JDK版本搭配即可 2.Pom配置 串口通信包:

    2024年02月13日
    浏览(32)
  • Labview串口通信VISA实现串口收发

    前面使用过调用 MSComm 控件的方式(Labview串口通信MSComm实现串口收发),即利用 Windows 提供的控件对象,在 LabVIEW 中对该控件的属性和方法进行操作,来实现串口通信。之所以使用 MSComm 控件,是因为比使用 VISA 来实现串口通信要灵活一些,比如可以通过回调的方式,在 PC 的

    2024年02月15日
    浏览(28)
  • Labview串口通信MSComm实现串口收发

    本文介绍使用 ActiveX 控件 MSComm 实现高性能的串口收发。 MSComm 作为一个串行通讯控件,每个 MSComm 控件,都对应一个串口,若需访问多个串口时必须使用多个 MSComm 控件。 MSComm 是 ActiveX 控件,可以在 PC 上控制串口数据的发送和接收,支持查询方式和中断方式(Windows 下称为事

    2024年02月15日
    浏览(32)
  • 【Python】串口通信-与FPGA、蓝牙模块实现串口通信(Python+FPGA)

    🎉欢迎来到Python专栏~与FPGA、蓝牙模块实现串口通信 ☆* o(≧▽≦)o *☆ 嗨 ~我是 小夏与酒 🍹 ✨ 博客主页: 小夏与酒的博客 🎈该系列 文章专栏: Python学习专栏 文章作者技术和水平有限,如果文中出现错误,希望大家能指正🙏 📜 欢迎大家关注! ❤️ Python与FPGA串口通信

    2024年02月15日
    浏览(34)
  • STM32 串口 DMA 数据读取(详细代码)

    最近重新开始学32,搞到串口 DMA 的时候, 数据读取卡了很长一段时间,最终,功夫不负有心人终于搞出来了。在此以记录一下,方便以后查询使用。 在调试的过程中也遇到了很多bug,有些简直就是低级问题,但是还是卡了很久,在此写出来给自己加深印象,同时已给后来者

    2024年02月16日
    浏览(31)
  • 串口通信实现-串口发送(vivado&verilog版)

    串口系列知识分享: (1)串口通信实现-串口发送 (2)串口通信发送多字节数据 (3)串口通信实现-串口接收 (4)UART 通信-使用VIO进行板级验证 (5)串口接收-控制LED闪烁 (6)使用串口发送实现ACX720开发板时钟显示 (7)串口发送+RAM+VGA传图 此文介绍uart串口协议(串口发

    2024年02月14日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包