使用Java语言实现串口通信
1.导入Meven坐标
<dependency>
<groupId>org.scream3r</groupId>
<artifactId>jssc</artifactId>
<version>2.8.0</version>
</dependency>
2.通过jssc.SerialPortList类获取串口列表
String[] portNames = SerialPortList.getPortNames(); //获取串口列表(COM1,COM2...)
3.通过jssc.SerialPort类创建串口对象
serialPort = new SerialPort(PORT_NAME);
4.设置串口参数,并且打开串口
// 打开端口
serialPort.openPort();
// 设置串口参数
serialPort.setParams(SerialPort.BAUDRATE_115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
System.out.println("Port opened successfully.");
5.串口数据发送
serialPort.writeBytes(buffer); //串口数据发送
6.手动串口数据接收
String readString = serialPort.readString(); //获取串口接收到的字符串数据,最好延时100ms后再读取,否则可能接收不到
7.关闭串口
if (serialPort != null && serialPort.isOpened()) {
try {
serialPort.closePort();
System.out.println("Port closed successfully.");
} catch (SerialPortException ex) {
System.out.println("Error closing port: " + ex.getMessage());
}
}
串口demo:通过100ms为周期给指定串口发送AT命令,并且将返回的RSSI写入指定的文件里(采集100个数据,使用逗号作为分隔符)
附完整代码
package com.example;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;
public class Main {
public static String PORT_NAME = "COM18";
public static SerialPort serialPort;
public static String DataSource = "D:\\L-CASCD12-BD01A\\LTE";
public static FileOutputStream fStream;
public static SimpleDateFormat fDateFormat;
public static void openPort() {
// 获取可用端口列表
String[] portNames = SerialPortList.getPortNames();
for (String port : portNames) {
if (PORT_NAME.equals(port)) {
serialPort = new SerialPort(PORT_NAME);
try {
// 打开端口
serialPort.openPort();
// 设置串口参数
serialPort.setParams(SerialPort.BAUDRATE_115200,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
System.out.println("Port opened successfully.");
return;
} catch (SerialPortException ex) {
System.out.println("Error opening port: " + ex.getMessage());
}
}
}
System.out.println("Port not found.");
}
public static void sendCommand(String command) {
try {
// 发送数据
byte[] buffer = command.getBytes();
serialPort.writeBytes(buffer);
// System.out.println("Command sent: " + command);
} catch (SerialPortException ex) {
System.out.println("Error sending command: " + ex.getMessage());
}
}
public static void readResponse() {
int im = 0;
while (true) {
try {
sendCommand("AT+ECRFNST=00572900526703000000\r\n");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String readString = serialPort.readString();
if (readString != null) {
String[] split = readString.split("MT00000400");
StringBuffer buffer = new StringBuffer();
char[] charArray = split[1].substring(0, split[1].length() - 4).toCharArray();
int length = charArray.length;
if (length % 2 != 0) {
System.out.println("input error");
continue;
}
for (int i = 0; i < length; i += 2) {
buffer.append(charArray[length - i - 2]);
buffer.append(charArray[length - i - 1]);
}
// System.out.println(buffer.toString());
try {
long parseInt = Long.parseLong(buffer.toString(), 16);
// System.out.println(convertComplementToOriginal(parseInt));
parseInt = parseInt ^ 0xffffffffL;
// parseInt = ~parseInt + 1;
// System.out.println((parseInt));
// parseInt ^= 0xffffffffL;
// parseInt = parseInt + 1;
// parseInt = -((~parseInt) + 1);
double rssi = -(parseInt + 1) / 16.0f;
fStream.write(((rssi + ",").getBytes()));
im++;
fStream.flush();
System.out.println(rssi);
if (im == 100) {
break;
}
} catch (Exception exception) {
System.out.println("input error");
}
// System.out.println(split[1]);
}
// 读取响应
// byte[] buffer = serialPort.readBytes(1); // 假设最多读取10个字节
// System.out.println(new String(buffer));
// String response = new String(buffer).trim();
// System.out.println("Response received: " + response);
// System.out.println(readString);
} catch (SerialPortException ex) {
System.out.println("Error reading response: " + ex.getMessage());
}
}
}
public static void closePort() {
if (serialPort != null && serialPort.isOpened()) {
try {
serialPort.closePort();
System.out.println("Port closed successfully.");
} catch (SerialPortException ex) {
System.out.println("Error closing port: " + ex.getMessage());
}
}
}
public static void main(String[] args) {
fDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
try {
File Source = new File(DataSource);
if (Source.exists() == false) {
Source.mkdirs();
}
String souString = DataSource + "\\rssi_data_" + fDateFormat.format(new Date()) + ".txt";
System.out.println(souString);
fStream = new FileOutputStream(
new File(souString));
} catch (Exception e) {
System.out.println(e.getMessage());
}
openPort();
readResponse();
closePort();
System.out.println("Hello world!");
}
}
评论