CSharp串口通信
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
using System;
using System.Collections.Generic;
using ponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace SerialPorts
{
public partial class frm_Main : Form
{
#region Public Enumerations
public enum DataMode { Text, Hex }
public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
#endregion
private Color[] LogMsgTypeColor = { Color.Orange, Color.Green, Color.Black, Color.Blue, Color.Red }; //禁用和启用程序中各控件的状态
private void EnableControls()
{
// 基于串口的打开与否,设置控件状态
gbPortSettings.Enabled = !ComPort.IsOpen;
btns.Enabled = btnstop.Enabled = txtSendData.Enabled = btnSend.Enabled = ComPort.IsOpen;
if (ComPort.IsOpen) btnOpenPort.Text = "关闭串口";
else btnOpenPort.Text = "打开串口";
}
//初始化组件的数据,为串口提供相关参数
private void InitializeControlValues()
{
cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));
cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));
cmbPortName.Items.Clear();
foreach (string s in SerialPort.GetPortNames())
cmbPortName.Items.Add(s);
cmbPortName.Text = cmbPortName.Items[0].ToString();
cmbParity.Text = cmbParity.Items[0].ToString();
cmbStopBits.Text = cmbStopBits.Items[0].ToString();
cmbDataBits.Text = cmbDataBits.Items[0].ToString();
cmbParity.Text = cmbParity.Items[0].ToString();
cmbBaudRate.Text = cmbBaudRate.Items[0].ToString();
EnableControls();
}
//十六进制转换字节数组
private byte[] HexStringToByteArray(string s)
{
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}
//字节数组转换十六进制
private string ByteArrayToHexString(byte[] data)
{
StringBuilder sb = new StringBuilder(data.Length * 3);
foreach (byte b in data)
sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
return sb.ToString().ToUpper();
}
//显示数据日志
private void Log(LogMsgType msgtype, string msg)
{
rtfTerminal.Invoke(new EventHandler(delegate
{
rtfTerminal.SelectedText = string.Empty;
rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold); rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
rtfTerminal.AppendText(msg);
rtfTerminal.ScrollToCaret();
}));
}
//串口发送方式
#region Local Properties
private DataMode CurrentDataMode
{
get
{
if (rbHex.Checked) return DataMode.Hex;
else return DataMode.Text;
}
set
{
if (value == DataMode.Text) rbText.Checked = true;
else rbHex.Checked = true;
}
}
#endregion
//发送数据