串口通讯
一、Java串口通讯助手
1、下载64位rxtx for java 链接:http://fizzed.com/oss/rxtx-for-java
2、解压安装所下载的文件
复制 RXTXcomm.jar ---> <JAVA_HOME>\jre\lib\ext
复制 rxtxSerial.dll ---> <JAVA_HOME>\jre\bin
复制 rxtxParallel.dll ---> <JAVA_HOME>\jre\bin
这俩文件一定要放入<JAVA_HOME>\jre\bin
目录下,不然会报如下错误:
no rxtxSerial in java.library.path thrown while loading gnu.io.RXTXCommDrive
3、添加pom文件
<dependency>
<groupId>org.rxtx</groupId>
<artifactId>rxtx</artifactId>
<version>2.1.7</version>
</dependency>
4、串口通讯助手代码
三个小功能:检查Ports,发送数据,接收数据
package com.suian.util;
import gnu.io.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
/**
* @author suian
* @date 2020/10/12 10:15
*/
public class SerialHelper {
//初始化参数
public static SerialPort serialPort;
private static String PORT_NAME = "COM2";//port名字
private static int BOUND_VAlUE = 9600; //波特率设置
private static int SerialPort_DATABITS = SerialPort.DATABITS_8;//数据位
private static int SerialPort_STOPBITS = SerialPort.STOPBITS_1;//停止位
private static int SerialPort_PARITY = SerialPort.PARITY_NONE;//奇偶校验
//发送数据
public static void sendData(String datas) throws Exception {
//打开串口
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(PORT_NAME);
CommPort commPort = portIdentifier.open(PORT_NAME, 2000);//2000是超时时间
serialPort = (SerialPort) commPort;
//设置参数 (波特率,输入/输出控制,数据位,停止位和奇偶校验)
serialPort.setSerialPortParams(BOUND_VAlUE, SerialPort_DATABITS, SerialPort_STOPBITS, SerialPort_PARITY);
//发送数据
OutputStream outputStream = null;
try {
outputStream = serialPort.getOutputStream();
outputStream.write(datas.getBytes());
outputStream.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
outputStream.close();
}
//设置当有数据到达时,唤醒监听接收线程
serialPort.notifyOnDataAvailable(true);
//设置当通信中断时唤醒中断线程
serialPort.notifyOnBreakInterrupt(true);
}
//接收数据
public static void receiveData() throws Exception {
//打开串口
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(PORT_NAME);
CommPort commPort = portIdentifier.open(PORT_NAME, 2000);//2000是超时时间
serialPort = (SerialPort) commPort;
//设置参数 (波特率,输入/输出控制,数据位,停止位和奇偶校验)
serialPort.setSerialPortParams(BOUND_VAlUE, SerialPort_DATABITS, SerialPort_STOPBITS, SerialPort_PARITY);
//接收数据
serialPort.addEventListener((serialPortEvent) -> { //匿名内部类实现SerialPortEventListener接口的类,具体读操作在里面进行
if (serialPortEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
InputStream in = null;
byte[] bytes = null;
try {
in = serialPort.getInputStream();
int buffSize = in.available();
while (buffSize != 0) {
//初始化byte 数组为buffer中数据的长度
bytes = new byte[buffSize];
in.read(bytes);
System.out.println(new String(bytes));
buffSize = in.available();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
//设置当有数据到达时,唤醒监听接收线程
serialPort.notifyOnDataAvailable(true);
//设置当通信中断时唤醒中断线程
serialPort.notifyOnBreakInterrupt(true);
}
//串口检测
public static void CheckPorts() {
Enumeration<CommPortIdentifier> em = CommPortIdentifier.getPortIdentifiers();
while (em.hasMoreElements()) {
String name = em.nextElement().getName();
System.out.println("串口检测: " + name);
}
}
}
二、C#串口通讯
软件界面如下:
直接贴代码:
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace demo13
{
public partial class Form1 : Form
{
#region 公共数据
bool isOpened = false;//串口状态标志
#endregion
public Form1()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;//设置该属性 为false
}
private void Form1_Load(object sender, EventArgs e)
{
//检测com口,并设置默认波特率
RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
if (keyCom != null)
{
string[] sSubKeys = keyCom.GetValueNames();
cmbPort.Items.Clear();
foreach (string sName in sSubKeys)
{
string sValue = (string)keyCom.GetValue(sName);
cmbPort.Items.Add(sValue);
}
if (cmbPort.Items.Count > 0)
cmbPort.SelectedIndex = 0;
}
cmbBaud.Text = "115200";
}
private void button1_Click(object sender, EventArgs e)
{
if (!isOpened)
{
serialPort.PortName = cmbPort.Text;//串口名称
serialPort.BaudRate = Convert.ToInt32(cmbBaud.Text, 10);//波特率设置
try
{
serialPort.Open(); //打开串口
button1.Text = "关闭串口";
cmbPort.Enabled = false;//关闭使能
cmbBaud.Enabled = false;
isOpened = true;
serialPort.DataReceived += new SerialDataReceivedEventHandler(post_DataReceived);//串口接收处理函数
}
catch
{
MessageBox.Show("串口打开失败!");
}
}
else
{
try
{
serialPort.Close(); //关闭串口
button1.Text = "打开串口";
cmbPort.Enabled = true;//打开使能
cmbBaud.Enabled = true;
isOpened = false;
}
catch
{
MessageBox.Show("串口关闭失败!");
}
}
}
//接收处理函数
private void post_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string str = serialPort.ReadExisting();//字符串方式读
ReceiveTbox.Text = "";//先清除上一次的数据
ReceiveTbox.Text += str;
}
//数据发送
private void button2_Click(object sender, EventArgs e)
{
//发送数据
if (serialPort.IsOpen)
{//如果串口开启
if (SendTbox.Text.Trim() != "")//如果框内不为空则
{
serialPort.Write(SendTbox.Text.Trim());//写数据
}
else
{
MessageBox.Show("发送框没有数据");
}
}
else
{
MessageBox.Show("串口未打开");
}
}
}
}
三、虚拟串口助手
汉化过的虚拟串工具,可以去我上传的资源里找下
虚拟串口工具下载