java通过串口通信获取传感器数据的步骤流程
·
**序言:**在Java中通过串口通信获取温度传感器数据,通常需要使用一些第三方库来帮助实现串口通信。最常用的库之一是RXTX或Java Simple Serial Connector (jSSC)。以下是使用jSSC库通过串口获取温度传感器数据的基本步骤:
步骤 1: 添加jSSC库
首先,你需要将jSSC库添加到你的项目中。如果你使用Maven,可以在pom.xml中添加以下依赖:
<dependency>
<groupId>org.scream3r</groupId>
<artifactId>jssc</artifactId>
<version>2.8.0</version>
</dependency>
步骤 2: 配置串口参数
在Java代码中,你需要配置串口的参数,比如波特率、数据位、停止位和校验位。这些参数通常由温度传感器的数据手册提供。
步骤 3: 打开串口并读取数据
接下来,使用jSSC打开串口,并读取数据。下面是一个简单的示例代码:
import jssc.SerialPort;
import jssc.SerialPortException;
public class SerialPortExample {
public static void main(String[] args) {
SerialPort serialPort = new SerialPort("COM3"); // 替换为你的串口号
try {
serialPort.openPort(); // 打开端口
serialPort.setParams(SerialPort.BAUDRATE_9600, // 设置波特率
SerialPort.DATABITS_8, // 数据位
SerialPort.STOPBITS_1, // 停止位
SerialPort.PARITY_NONE); // 无校验位
while (true) {
String data = serialPort.readString(); // 读取数据
if (data != null && !data.isEmpty()) {
System.out.println("Received data: " + data); // 打印接收到的数据
// 解析数据并处理温度值,例如:
String[] parts = data.split(","); // 假设数据格式为温度值,其他值,其他值,...
if (parts.length > 0) {
try {
float temperature = Float.parseFloat(parts[0]); // 假设第一个部分是温度值
System.out.println("Temperature: " + temperature + " °C"); // 打印温度值
} catch (NumberFormatException e) {
System.err.println("Error parsing temperature value.");
}
}
}
Thread.sleep(100); // 稍微等待一下,减少CPU使用率
}
} catch (SerialPortException | InterruptedException ex) {
System.err.println("Error in serial communication: " + ex.getMessage());
} finally {
serialPort.closePort(); // 关闭端口
}
}
}
步骤 4: 打开串口并读取数据(ssM架构 Controller)
接下来,使用jSSC打开串口,并读取数据。下面是一个简单的示例代码:
@ResponseBody
@RequestMapping(value="/setInputId")
public String set_Entity(@RequestParam(value="inputId",required=false)String inputId ,HttpServletRequest request) {
JSONObject jsonObject=new JSONObject();
SerialPort serialPort = null;
try {
// 假设我们使用第一个端口
serialPort = new SerialPort("COM3");
serialPort.openPort();
serialPort.setParams(SerialPort.BAUDRATE_9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
while (true) {
// 发送字符串数据
String dataToSend = "\n" + inputId; // 注意根据传感器协议调整结束符
serialPort.writeString(dataToSend); //发送命令值
String dataToRead=serialPort.readString();//接收命令值
if(dataToRead!=null) {
// System.out.println("数据发送的值: " + dataToSend);
System.out.println("数据接收到的值: =========");
System.out.println(dataToRead);//数据接收到的值
jsonObject.put("outputId", dataToRead);//传递给前端值
//System.out.println("数据接收到的值: =========" + dataToRead);
break;//跳出 while循环
}
try {
Thread.sleep(100);//等待1秒访问
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 稍微等待一下,减少CPU使用率
}
serialPort.closePort();//关闭串口
} catch (SerialPortException ex) {
System.out.println("There was an error opening the port.");
ex.printStackTrace();
}
finally {
}
return jsonObject.toString();
}
步骤 5: 前端内容html内容
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0" />
<title>传感器读取展示界面</title>
<link rel="stylesheet" href="${pageContext.request.contextPath }/statics/common/commonCss/bootstrap.min.css" />
<link rel="stylesheet" href="${pageContext.request.contextPath }/statics/common/demo.css" />
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/common/commonJs/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/common/commonJs/bootstrap.min.js"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath }/statics/layui/css/layui.css">
</head>
<style>
.mgt20 {
margin-top: 20px;
margin-bottom: 20px;
}
.stream-div {
width: 500px;
height: 200px;
background-color: var(--bs-gray-300);
overflow: auto;
margin-left: 100px;
margin-top: -20px;
color: var(--bs-primary);
border: 2px solid #6ac8db;
border-radius: 5px;
padding: 20px;
font-size: 20px;
}
/*滚动条设置*/
::-webkit-scrollbar{
width: 3px;
height: 2px;
background-color: #ad7842e0;
border-radius: 100px;
}
/*滚动条上的滚动滑块*/
::-webkit-scrollbar-thumb{
/* height: 5px;*/
border-radius: 100px;
background-color: rgb(227 49 49 / 58%);
}
.common-btn-open {
width: 240px;
height: 50px;
margin-left: 100px;
font-size: 22px;
border-radius: 10px;
}
.common-btn-close {
width: 230px;
height: 50px;
background-color: #783131;
margin-left: 20px;
font-size: 22px;
border-radius: 10px;
}
.common-btn-jieshou{
width: 150px;
font-size: 20px;
font-weight: 600;
}
.sec-title {
font-size: 18px;
width: 500px;
font-size: 30px;
color: #2c9f9f;
margin-left: 110px;
font-weight: 600;
margin-bottom: 10px;
text-align: center;
letter-spacing: 3px;
border: 5px #3db793 solid;
border-radius: 10px;
}
</style>
<%-- ${saveUrl} --%>
<body>
<div class="demo-box">
<div class="title">传感器读取Demo</div>
<div class="content">
<!-- 左侧导航栏 -->
<!-- <div class="nav-box">
<ul class="nav nav-pills" role="tablist" id="mainTabs">
<li role="presentation" class="nav-link list-group-item active-item"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">HLS 视频流播放</a></li>
<li role="presentation" class="nav-link list-group-item"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">FLV 视频流播放</a></li>
</ul>
</div> -->
<!-- tab主要内容 -->
<div class="tab-content content-box">
<!-- HLS 播放 -->
<div role="tabpanel" class="tab-pane active" id="home">
<!-- 步骤引导 -->
<!-- <div class="common-step play-step">
<div class="sec-title">HLS视频流播放步骤</div>
<div class="step-box">
<div class="step-item">1. 获取HLS实时流地址(如何获取流地址请查看<a href="https://open-icc.dahuatech.com/hlsplayer/#5">HLS详细说明</a>),获取HLS录像回放流地址(如何获取流地址请查看<a href="https://open-icc.dahuatech.com/#/home?url=%3Fnav%3Dwiki%2Fadmin%2Freplay.html&version=enterprisebase/5.0.15&blank=true">详细说明</a>)</div>
<div class="line-with-arrow"></div>
<div class="step-item">3. 播放配置输入流地址</div>
<div class="step-item">4. 开始播放</div>
</div>
</div> -->
<!-- 播放配置-->
<div class="common-step play-setting">
<div class="sec-title">传感器读取数据的操作命令</div>
<div id="oneInput" class="mgt20 mgl10">
<!--<label >发送数据:</label>
<input type="text" class="stream-input" id="inputData" placeholder="请发送数据" value="">
<button class="common-btn" id="oneStart">发送</button> -->
<button class="common-btn common-btn-open" id="oneStart">点击读取数据</button>
<button class="common-btn common-btn-close" id="oneClose">关闭读取数据</button>
<br><br>
<label class="common-btn-jieshou">接收数据:</label>
<!-- <input type="text" class="stream-input" id="outputData" value=""> -->
<div class="stream-div" id="outputData" >
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/statics/layui/layui.js"></script>
<script type="text/javascript">
// 定义定时器变量
let intervalId;
// 设置定时器
function startTimer() {
intervalId = setInterval( "duqu()" , 5*1000);
}
// 取消定时器
function stopTimer() {
clearInterval(intervalId);//取消定时器Id
//想在1秒内清理掉 outputData 内的数据
setTimeout(function() {
$('#outputData').html("");//清空文本框中的数据
console.log('取消文本框中的内容');
}, 1000);
}
// 绑定按钮点击事件
//document.getElementById('oneStart').addEventListener('click', startTimer);
//document.getElementById('oneClose').addEventListener('click', stopTimer);
//响应事件
$(function() {
//开启
$(document).on("click","#oneStart",function(){
startTimer(); // 调用定时器
//启动命令提醒
layui.use(function() {
var layer = layui.layer;
layer.msg('启动读取数据', {
icon: 6,
time:2000
});
});
})
//关闭
$(document).on("click","#oneClose",function(){
stopTimer(); // 调用 取消定时器
//关闭命令提醒
layui.use(function() {
var layer = layui.layer;
layer.msg('关闭读取数据', {
icon: 6,
time:1000
});
});
})
})
//*******读取数据的函数duqu()
function duqu(){
$(function(){
//获取发送命令 的数据
var inputId = $("#inputData").val();
//异步请求处理,开始进行传感器数据命令请求 输出
$.ajax({
async:false,
type:"post",
url:"${pageContext.request.contextPath }/sp/setInputId",
data:{inputId:inputId},
dataType:"json",
success:function(data){
//输出传感器参数
console.log("outputId===="+data.outputId);
//$("#outputData").val(data.outputId);
// 使用jQuery追加内容
$('#outputData').append("<p>"+ data.outputId +"</p>");
},
error:function(){
//layer.msg('出现异常');
}
});
})
}
$(document).on("click","",function(){
//获取发送命令 的数据
var inputId = $("#inputData").val();
//异步请求处理,开始进行传感器数据命令请求 输出
$.ajax({
async:true,
type:"post",
url:"${pageContext.request.contextPath }/sp/setInputId",
data:{inputId:inputId},
dataType:"json",
success:function(data){
//输出传感器参数
console.log("outputId===="+data.outputId);
//$("#outputData").val(data.outputId);
// 使用jQuery追加内容
$('#outputData').append("<p>"+ data.outputId +"</p>");
},
error:function(){
//layer.msg('出现异常');
}
});
})
</script>
</html>
步骤 6: 页面中所需的插件
链接:所需的资源下载
https://download.csdn.net/download/qq_39951524/90464845
最后:谢谢各位的浏览
工作几年,略有心得,然很少整理成文,平常工作中浏览了不少道友的好文章,受益良多。
顾也开始写一些文章, 希望能与各位道友分享进步 !!!!
如果有用,欢迎各位点赞评论,若有不足,亦可指正!!!
更多推荐
所有评论(0)