投影串口测试程序_【原创】串口通信测试程序

这是一个使用C#编写的串口通信程序,包含打开、关闭串口、设置串口参数、发送及接收数据等功能。通过初始化串口、设置波特率、数据位、奇偶校验和停止位,实现与硬件设备的通信。程序还提供了读取和显示通信日志,以及清除日志的选项。
摘要由CSDN通过智能技术生成

源代码:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Threading;

namespace 串口通信

{

public partial class frmMain : Form

{

public frmMain()

{

InitializeComponent();

}

public int iPort = 1; //1,2,3,4

public int iRate = 9600; //1200,2400,4800,9600

public byte bSize = 8; //8 bits

public byte bParity = 0; // 0-4=no,odd,even,mark,space

public byte bStopBits = 1; // 0,1,2 = 1, 1.5, 2

public int iTimeout = 1000;

public myCom com = new myCom();

public byte[] recb;

public int nub = 0;

//打开串口

public bool openCom()

{

try {

if (com.Opened)

{

com.Close();

com.Open();

}

else

{

com.Open();

}

return true;

}catch(Exception ex)

{

MessageBox.Show(ex.Message);

return false;

}

}

//显示包信息

public string disPackage(byte[] reb)

{

string temp = "";

foreach (byte b in reb)

temp += b.ToString("X2") + " ";

return temp;

}

//去掉字符数组中的空格

public string delSpace(string input)

{

string output = "";

for(int i=0;i

{

if(input!=' ')

output += input;

}

return output;

}

//发送数据包

public void sendPackage(byte[] bb)

{

int sendNum = 0;

try

{

sendNum = com.Write(bb);

Thread.Sleep(50);

this.txtShow.AppendText("\r\n发送数据:"+disPackage(bb));

recb = com.Read(50);

this.txtShow.AppendText("\r\n接收到数据:" + disPackage(recb));

}catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

//提取发送的数据包

public byte[] sendDB()

{

string temp = delSpace(this.txtSend.Text.Trim());

byte[] strTemp = new byte[50];

int j = 0;

try

{

for (int i = 0; i < temp.Length; i = i + 2, j++)

strTemp[j] = Convert.ToByte(temp.Substring(i, 2), 16);

}catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

byte[] send = new byte[j];

Array.Copy(strTemp, send, j);

return send;

}

//点击发送按钮发送数据

private void button4_Click(object sender, EventArgs e)

{

if (this.txtSend.Text == "")

{

MessageBox.Show("发送数据为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);

return;

}

if (com.Opened)

{

byte[] temp = se

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值