串口调试助手简介:
串口调试助手是串口调试相关工具,有多个版本。如:友善串口调试助手,支持9600,19200等常用各种波特率及自定义波特率,可以自动识别串口,能设置校验、数据位和停止位,能以ASCII码或十六进制接收或发送任何数据或字符,可以任意设定自动发送周期,并能将接收数据保存成文本文件,能发送任意大小的文本文件。
硬件连接方面,传统台式PC机支持标准RS232接口,但是带有串口的笔记本很少见,所以需要USB/232转换接口,并且安装相应驱动程序。
主要实现的功能:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports; //导入串口的命名空间
namespace _01_SerialPort
{
public partial class Form1 : Form
{
public delegate void showReceiveDelegate(string text); //当采用响应模式,应申明一个委托,实现不同线程的控件实验
SerialPort com = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);//初始化构造函数
public Form1()
{
InitializeComponent();
}
///
/// 窗体加载
///
///
///
private void Form1_Load(object sender, EventArgs e)
{
cmbPort.SelectedIndex = 0;
cmbBaudRate.SelectedIndex = 0;
cmbDataBits.SelectedIndex = 0;
cmbStopBits.SelectedIndex = 0;
cmbParity.SelectedIndex = 0;
}
///
/// 串口打开与关闭
///
///
///
private void btnOpen_Click(object sender, EventArgs e)
{
if (btnOpen.Text == "打开串口")
{
try
{
if (!com.IsOpen)
{
com.PortName = cmbPort.Text;
com.BaudRate = int.Parse(cmbBaudRate.Text);
com.DataBits = int.Parse(cmbDataBits.Text);
switch (cmbStopBits.SelectedIndex) {
case 0:
com.StopBits = StopBits.One; break;
case 1:
com.StopBits = StopBits.Two; break;
case 2:
com.StopBits = StopBits.OnePointFive; break;
case 3:
com.StopBits = StopBits.None; break;
}
switch (cmbParity.SelectedIndex)
{
case 0: com.Parity = Parity.None; break;
case 1: com.Parity = Parity.Odd; break;
case 2: com.Parity = Parity.Even; break;
}
com.Open();//打开串口
}
btnOpen.Text = "关闭串口";
txtStatus.Text = "串口已打开!";
btnSend.Enabled = true;
if (rbAck.Checked)
btnReceive.Enabled = true; //应答模式,接收按钮有效
}
catch
{ txtStatus.Text = "串口打开错误或串口不存在!"; }
}
else //关闭串口
try
{
if (com.IsOpen)
com.Close(); //关闭串口
btnOpen.Text = "打开串口";
txtStatus.Text = "串口已关闭!";
btnSend.Enabled = false ;
if (rbAck.Checked)
btnReceive.Enabled = false; //应答模式,接收按钮有效
}
catch
{ txtStatus.Text = "串口关闭错误或串口不存在!"; }
}
///
/// 串口发送数据
///
///
///
private void btnSend_Click(object sender, EventArgs e)
{
try
{
byte[] data = null;
if(chkSendHex.Checked)
data = getBytesFromString(txtSend.Text);
else
data = Encoding.Default.GetBytes(txtSend.Text);
com.Write(data, 0, data.Length);
}
catch (Exception err)
{ txtStatus.Text = err.ToString(); }
}
///
/// 串口接收数据,应答模式时
///
///
///
private void btnReceive_Click(object sender, EventArgs e)
{
try
{
//应答模式
int count = com.BytesToRead;
byte[] readBuffer = new byte[count];
com.Read(readBuffer, 0, count);
if (chkRecHex.Checked)
txtReceive.Text = getStringFromBytes(readBuffer); //转十六进制
else
txtReceive.Text = Encoding.Default.GetString(readBuffer); //字母、数字、汉字转换为字符串
}
catch (Exception err)
{ txtStatus.Text = err.ToString(); }
}
///
/// 数据接收模式变化时,设置串口的数据接收侦听事件
///
///
///
private void rbResponse_CheckedChanged(object sender, EventArgs e)
{
try
{ btnReceive.Enabled = rbAck.Checked;
if(rbResponse.Checked)
com.DataReceived += new SerialDataReceivedEventHandler(com_DataReceived); //加载接收事件
else
com.DataReceived -= new SerialDataReceivedEventHandler(com_DataReceived); //移除接收事件
}
catch (Exception err)
{ txtStatus.Text = err.ToString(); }
}
///
/// 响应模式时,串口接收数据事件
///
///
///
private void com_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{ try
{
int count = com.BytesToRead;
byte[] readBuffer = new byte[count];
com.Read(readBuffer, 0, count);
string strReceive="";
if(chkRecHex.Checked)
strReceive = getStringFromBytes(readBuffer); //转十六进制
else
strReceive = Encoding.Default.GetString(readBuffer); //字母、数字、汉字转换为字符串
this.Invoke(new showReceiveDelegate(doShowReceive), strReceive);
}
catch (Exception err)
{ txtStatus.Text = err.ToString(); }
}
///
/// //异步线程处理接受的字符,显示在接收的文本框中
///
///
public void doShowReceive(string str)
{
txtReceive.Text += str;
}
///
/// 以十六进制数据发送转换时,显示转换对应数据
///
///
///
private void chkSendHex_CheckedChanged(object sender, EventArgs e)
{ try
{
if (chkSendHex.Checked)
txtSend.Text = getStringFromBytes( Encoding.Default.GetBytes(txtSend.Text));
else
txtSend.Text =Encoding.Default.GetString(getBytesFromString(txtSend.Text));
}
catch
{ txtStatus.Text = "数据转换出错,请输入正确的数据格式"; }
}
///
/// 以十六进制数据显示接收数据时,显示对应数据
///
///
///
private void chkRecHex_CheckedChanged(object sender, EventArgs e)
{
try
{ if (chkRecHex.Checked)
txtReceive.Text = getStringFromBytes(Encoding.Default.GetBytes(txtReceive.Text));
else
txtReceive.Text = Encoding.Default.GetString(getBytesFromString(txtReceive.Text));
}
catch
{ txtStatus.Text ="数据转换出错,请输入正确的数据格式"; }
}
///
/// 把十六进制格式的字符串转换成字节数组。
///
/// 要转换的十六进制格式的字符串
/// 返回字节数组。
public static byte[] getBytesFromString(string pString)
{
string[] str = pString.Split(' '); //把十六进制格式的字符串按空格转换为字符串数组。
byte[] bytes = new byte[str.Length]; //定义字节数组并初始化,长度为字符串数组的长度。
for (int i = 0; i < str.Length; i++) //遍历字符串数组,把每个字符串转换成字节类型赋值给每个字节变量。
bytes[i] = Convert.ToByte(Convert.ToInt32(str[i], 16));
return bytes; //返回字节数组。
}
///
/// 把字节数组转换为十六进制格式的字符串。
///
/// 要转换的字节数组。
/// 返回十六进制格式的字符串。
public static string getStringFromBytes(byte[] pByte)
{
string str = ""; //定义字符串类型临时变量。
//遍历字节数组,把每个字节转换成十六进制字符串,不足两位前面添“0”,以空格分隔累加到字符串变量里。
for (int i = 0; i < pByte.Length; i++)
str += (pByte[i].ToString("X").PadLeft(2, '0') + " ");
str = str.TrimEnd(' '); //去掉字符串末尾的空格。
return str; //返回字符串临时变量。
}
}
}
相关项目文件可在上传的资源里找到