基于Modbus的C#串口调试开发

说明:本文主要研究的是使用C# WinForm开发的串口调试软件(其中包含Modbus协议相关操作)。Modbus相关协议可以查阅百度文库等,可参考: 《http://wenku.baidu.com/link?url=J-QZeQVLfvfZh7_lh8Qf0MdwANZuVjEoTqox6zJYrSnKyfgES2RTb_bjC5ZTn8-xgsuUAyiELRYVA3-3FBkBGywWhQ9YGoavJOzwB0IxTyK 》。

  (1)先测试串口设置,发送和接收数据。

  (2)发送modbus的命令帧数据和使用DataReceived接收缓冲区的数据。

一、简单的串口调试工具

  下图为串口调试工具的界面,主要包括串口基本设置,功能操作,状态框以及发送接收框。由于这里只是简单的初始化数据,所以当需要发送数据的时候需要点击“串口检测”,来测试当前可用的串口,然后输入需要发送的数据,最后点击“发送数据”(由于测试需要,让发送什么数据就返回什么数据,这里的底层硬件做了短接处理,使用短接貌P30-P31,具体操作可以自行百度)

  基于Modbus的C#串口调试开发

  

  1.1 发送数据操作

    (1)点击 串口检测

    (2)输入发送数据

    (3)点击 发送数据

    下面开始时具体代码:

    #1 软件打开时候初始化操作:Form1_Load(),主要初始化操作串口设置的下拉列表。

 private void Form1_Load(object sender, EventArgs e)
{ //设置窗口大小固定
this.MaximumSize = this.Size;
this.MinimumSize = this.Size; //1、设置串口下拉列表
for ( int i = ; i < ; i++ )
{
cbxCOMPort.Items.Add("COM" + (i + ).ToString());
}
cbxCOMPort.SelectedIndex = ;//默认选项 //2、设置常用波特率
int bt = ;
for (int i = ; i < ; i++)
{
cbxBaudRate.Items.Add(bt.ToString());
bt *= ;
} cbxBaudRate.Items.Add("");
cbxBaudRate.Items.Add("");
cbxBaudRate.Items.Add("");
cbxBaudRate.Items.Add("");
cbxBaudRate.Items.Add("");
cbxBaudRate.SelectedIndex = ; //3、列出停止位
cbxStopBits.Items.Add("");
cbxStopBits.Items.Add("");
cbxStopBits.Items.Add("1.5");
cbxStopBits.Items.Add("");
cbxStopBits.SelectedIndex = ; //4、设置奇偶检验
cbxParity.Items.Add("无");
cbxParity.Items.Add("奇校验");
cbxParity.Items.Add("偶校验");
cbxParity.SelectedIndex = ; //5、设置数据位
cbxDataBits.Items.Add("");
cbxDataBits.Items.Add("");
cbxDataBits.Items.Add("");
cbxDataBits.Items.Add("");
cbxDataBits.SelectedIndex = ; }

private void Form1_Load(object sender, EventArgs e)

    

    #2 检查串口基本设置的参数:CheckPortSetting(),

 /// <summary>
/// 【检测端口设置】
/// </summary>
/// <returns></returns>
private bool CheckPortSetting()
{
//检测端口设置
if (cbxCOMPort.Text.Trim() == "" || cbxBaudRate.Text.Trim() == "" || cbxStopBits.Text.Trim() == "" || cbxParity.Text.Trim() == "" || cbxDataBits.Text.Trim() == "")
return false;
return true;
}

private bool CheckPortSetting()

    #3 设置串口属性,创建SerialPort对象  

 /// <summary>
/// 【设置串口属性】
/// </summary>
private void SetPortProperty()
{
//1、设置串口的属性
sp = new SerialPort(); sp.ReceivedBytesThreshold = ;//获取DataReceived事件发生前内部缓存区字节数
sp.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);//设置委托 sp.PortName = cbxCOMPort.Text.Trim(); //2、设置波特率
sp.BaudRate = Convert.ToInt32( cbxBaudRate.Text.Trim()); //3、设置停止位
float f = Convert.ToSingle( cbxStopBits.Text.Trim()); if (f == )
{
sp.StopBits = StopBits.None;//表示不使用停止位
}
else if (f == 1.5)
{
sp.StopBits = StopBits.OnePointFive;//使用1.5个停止位
}
else if (f == )
{
sp.StopBits = StopBits.Two;//表示使用两个停止位
}
else
{
sp.StopBits = StopBits.One;//默认使用一个停止位
} //4、设置数据位
sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim()); //5、设置奇偶校验位
string s = cbxParity.Text.Trim();
if (s.CompareTo("无") == )
{
sp.Parity = Parity.None;//不发生奇偶校验检查
}
else if (s.CompareTo("奇校验") == )
{
sp.Parity = Parity.Odd;//设置奇校验
}
else if (s.CompareTo("偶校验") == )
{
sp.Parity = Parity.Even;//设置偶检验
}
else
{
sp.Parity = Parity.None;
} //6、设置超时读取时间
sp.ReadTimeout = -; //7、打开串口
try
{
sp.Open();
isOpen = true;
}
catch(Exception)
{
lblStatus.Text = "打开串口错误!";
} }

private void SetPortProperty()

    

    #4 “发送数据”按钮点击事件:btnSend_Click(), 在发送数据需要进行,#2,#3验证,然后开始通过串口对象写入数据

     /// <summary>
/// 【发送数据】
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
//发送串口数据 //1、检查串口设置
if (!CheckPortSetting())
{
MessageBox.Show("串口未设置!", "错误提示");
return;
} //2、检查发送数据是否为空
if(tbxSendData.Text.Trim() == ""){
MessageBox.Show("发送数据不能为空");
return;
} //3、设置
if (!isSetProperty)
{
SetPortProperty();
isSetProperty = true;
} //4、写串口数据
if (isOpen)
{
//写出口数据
try
{
sp.Write(tbxSendData.Text);
tbxStatus.Text = "发送成功!"; tbxRecvData.Text += sp.ReadLine();//读取发送的数据 }
catch
{
tbxStatus.Text = "发送数据错误";
}
}
else
{
MessageBox.Show("串口未打开", "错误提示");
} }

  1.2 接受数据操作

    接收数据和发送数据有点类似   

 /// <summary>
/// 【读取数据】
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRecv_Click(object sender, EventArgs e)
{
if(isOpen) 
            { 
try 
                {
//读取串口数据
 
                    tbxRecvData.Text += sp.ReadLine()+"\r\n"; 
                } 
                catch(Exception) 
                { 
                    lblStatus.Text = "读取串口时发生错误!"; 
                    return; 
                } 
            } 
            else 
            { 
              MessageBox.Show("串口未打开!", "错误提示"); 
              return;              } 
}

  最后附上该窗体的后台代码:Form1.cs 

 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.Threading.Tasks;
using System.Windows.Forms; namespace 串口调试
{
public partial class Form1 : Form
{
SerialPort sp = null; bool isOpen = false;//是否打开 bool isSetProperty = false;//是否通过串口设置 public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{ //设置窗口大小固定
this.MaximumSize = this.Size;
this.MinimumSize = this.Size; //1、设置串口下拉列表
for ( int i = ; i < ; i++ )
{
cbxCOMPort.Items.Add("COM" + (i + ).ToString());
}
cbxCOMPort.SelectedIndex = ;//默认选项 //2、设置常用波特率
int bt = ;
for (int i = ; i < ; i++)
{
cbxBaudRate.Items.Add(bt.ToString());
bt *= ;
} cbxBaudRate.Items.Add("");
cbxBaudRate.Items.Add("");
cbxBaudRate.Items.Add("");
cbxBaudRate.Items.Add("");
cbxBaudRate.Items.Add("");
cbxBaudRate.SelectedIndex = ; //3、列出停止位
cbxStopBits.Items.Add("");
cbxStopBits.Items.Add("");
cbxStopBits.Items.Add("1.5");
cbxStopBits.Items.Add("");
cbxStopBits.SelectedIndex = ; //4、设置奇偶检验
cbxParity.Items.Add("无");
cbxParity.Items.Add("奇校验");
cbxParity.Items.Add("偶校验");
cbxParity.SelectedIndex = ; //5、设置数据位
cbxDataBits.Items.Add("");
cbxDataBits.Items.Add("");
cbxDataBits.Items.Add("");
cbxDataBits.Items.Add("");
cbxDataBits.SelectedIndex = ; } /// <summary>
/// 【串口检测按钮】
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCheckCOM_Click(object sender, EventArgs e)
{
//1、检测哪些端口可用
cbxCOMPort.Items.Clear();
cbxCOMPort.Text = ""; lblStatus.Text = "执行中...";
string str = "";
for (int i = ; i < ; i++)
{
try
{
////把所有可能的串口都测试一遍,打开关闭操作,只有可用的串口才可会放到下拉列表中
SerialPort sp = new SerialPort("COM" + (i + ).ToString());
sp.Open();
sp.Close();
cbxCOMPort.Items.Add("COM" + (i + ).ToString());
}
catch
{
str += "COM" + (i + ).ToString() + "、";
continue;
}
} //如果当前下拉列表有可用的串口,则默认选择第一个
if(cbxCOMPort.Items.Count > )
cbxCOMPort.SelectedIndex = ;
lblStatus.Text = "完成";
tbxStatus.Text = str;
} /// <summary>
/// 【检测端口设置】
/// </summary>
/// <returns></returns>
private bool CheckPortSetting()
{
//检测端口设置
if (cbxCOMPort.Text.Trim() == "" || cbxBaudRate.Text.Trim() == "" || cbxStopBits.Text.Trim() == "" || cbxParity.Text.Trim() == "" || cbxDataBits.Text.Trim() == "")
return false;
return true;
} /// <summary>
/// 【检测发送数据是否为空】
/// </summary>
/// <returns></returns>
private bool CheckSendData()
{
if (tbxSendData.Text.Trim() == "")
return false;
return true;
} /// <summary>
/// 【设置串口属性】
/// </summary>
private void SetPortProperty()
{
//1、设置串口的属性
sp = new SerialPort(); sp.PortName = cbxCOMPort.Text.Trim(); //2、设置波特率
sp.BaudRate = Convert.ToInt32( cbxBaudRate.Text.Trim()); //3、设置停止位
float f = Convert.ToSingle( cbxStopBits.Text.Trim()); if (f == )
{
sp.StopBits = StopBits.None;//表示不使用停止位
}
else if (f == 1.5)
{
sp.StopBits = StopBits.OnePointFive;//使用1.5个停止位
}
else if (f == )
{
sp.StopBits = StopBits.Two;//表示使用两个停止位
}
else
{
sp.StopBits = StopBits.One;//默认使用一个停止位
} //4、设置数据位
sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim()); //5、设置奇偶校验位
string s = cbxParity.Text.Trim();
if (s.CompareTo("无") == )
{
sp.Parity = Parity.None;//不发生奇偶校验检查
}
else if (s.CompareTo("奇校验") == )
{
sp.Parity = Parity.Odd;//设置奇校验
}
else if (s.CompareTo("偶校验") == )
{
sp.Parity = Parity.Even;//设置偶检验
}
else
{
sp.Parity = Parity.None;
} //6、设置超时读取时间
sp.ReadTimeout = -; //7、打开串口
try
{
sp.Open();
isOpen = true;
}
catch(Exception)
{
lblStatus.Text = "打开串口错误!";
} } /// <summary>
/// 【发送数据】
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
//发送串口数据 //1、检查串口设置
if (!CheckPortSetting())
{
MessageBox.Show("串口未设置!", "错误提示");
return;
} 、检查发送数据是否为空
if (!CheckSendData())
{
MessageBox.Show("请输入要发送的数据!", "错误提示");
return;
} //3、设置
if (!isSetProperty)
{
SetPortProperty();
isSetProperty = true;
} //4、写串口数据
if (isOpen)
{
//写出口数据
try
{
sp.Write(tbxSendData.Text);
tbxStatus.Text = "发送成功!"; tbxRecvData.Text += sp.ReadLine()+"\r\n";
}
catch
{
tbxStatus.Text = "发送数据错误";
}
}
else
{
MessageBox.Show("串口未打开", "错误提示");
} } /// <summary>
/// 【读取数据】
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRecv_Click(object sender, EventArgs e)
{
if(isOpen) 
            { 
try 
                {
//读取串口数据
 
                    tbxRecvData.Text += sp.ReadLine()+"\r\n"; 
                } 
                catch(Exception) 
                { 
                    lblStatus.Text = "读取串口时发生错误!"; 
                    return; 
                } 
            } 
            else 
            { 
              MessageBox.Show("串口未打开!", "错误提示"); 
              return;              } 
} }
}

Form1.cs

二、基于Modbus协议的数据发送和接收

  这里主要是在前面的基础上,把发送和接收的数据进行格式化(符合Modbus的数据帧格式),如下左图所示,右图为加入Modbus协议的窗体,主要添加了命令帧的输入框组:

   基于Modbus的C#串口调试开发基于Modbus的C#串口调试开发

  

  2.1 获取字节的的高位和低位:WORD_LO()、WORD_HI()   

 /// <summary>
/// 【获取低位字节】
/// </summary>
/// <param name="crcCLo"></param>
/// <returns></returns>
public static byte WORD_LO(ushort crcCLo)
{
crcCLo = (ushort)(crcCLo & 0X00FF);
return (byte)crcCLo;
} /// <summary>
/// 【获取高位字节】
/// </summary>
/// <param name="crcHI"></param>
/// <returns></returns>
public static byte WORD_HI(ushort crcHI)
{
crcHI = (ushort)(crcHI >> & 0X00FF);
return (byte)crcHI;
}

WORD_LO() WORD_HI()

  

  2.2 CRC高位表和低位表 

  #region CRC高位表 byte[] _auchCRCHi
private static readonly byte[] _auchCRCHi = new byte[]//crc高位表
{
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
};
#endregion #region CRC低位表 byte[] _auchCRCLo
private static readonly byte[] _auchCRCLo = new byte[]//crc低位表
{
0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
0x43, 0x83, 0x41, 0x81, 0x80, 0x40
};
#endregion

CRC高低位表

  2.3 CRC校验方法:CRC16()

 /// <summary>
/// 【CRC校验】
/// </summary>
/// <param name="buffer">命令帧合适前6字节</param>
/// <param name="Sset">开始位</param>
/// <param name="Eset">结束位</param>
/// <returns>CRC校验码</returns>
public static ushort CRC16(Byte[] buffer, int Sset, int Eset)
{
byte crcHi = 0xff; // 高位初始化 byte crcLo = 0xff; // 低位初始化 for (int i = Sset; i <= Eset; i++)
{
int crcIndex = crcHi ^ buffer[i]; //查找crc表值 crcHi = (byte)(crcLo ^ _auchCRCHi[crcIndex]);
crcLo = _auchCRCLo[crcIndex];
} return (ushort)(crcHi << | crcLo);
}

public static ushort CRC16(Byte[] buffer, int Sset, int Eset)

  

  2.4 获取数据帧,把需要发送的数据格式化成Modbus协议数据帧

  

 /// <summary>
/// 【获取读数据命令,返回命令帧】
/// </summary>
/// <param name="mdaddr">地址码</param>
/// <param name="R_CMD">功能码</param>
/// <param name="min_reg">寄存器地址</param>
/// <param name="data_len">寄存器个数</param>
/// <param name="R_CMD_LEN">命令长度</param>
/// <returns></returns>
public byte[] GetReadFrame(byte mdaddr, byte R_CMD, ushort min_reg, ushort data_len, int R_CMD_LEN)
{
//主机命令帧格式
// 字节 功能描述 例子
//
// 1 地址码 0x01
// 2 功能码 0x03
// 3 寄存器地址高 0x00
// 4 寄存器地址低 0x00
// 5 寄存器个数高 0x00
// 6 寄存器个数低 0x02
// 7 CRC检验码低 0xC4
// 8 CRC校验码高 0x0B ushort crc;
byte[] message = new byte[]; //设置模块号
message[] = mdaddr;
//设置命令字
message[] = R_CMD; //设置开始寄存器
message[] = WORD_HI(min_reg);
message[] = WORD_LO(min_reg); //设置数据长度
message[] = WORD_HI(data_len);
message[] = WORD_LO(data_len); //设置 CRC
crc = CRC16(message, , R_CMD_LEN - ); message[] = WORD_HI(crc);//CRC校验码高位
message[] = WORD_LO(crc);//CRC校验码低位 return message;
}

  2.6 对于DataReceived的使用

    #1 设置委托和方法

        private delegate void myDelegate(byte[] readBuffer);     

 /// <summary>
/// 【显示接收返回的数据】
/// </summary>
/// <param name="resbuffer"></param>
public void ShowRst(byte[] resbuffer)
{
MyModbus modbus = new MyModbus();
tbxRecvData.Text += "Recv:" + modbus.SetText(resbuffer) + "\r\n";
}

    #2 设置属性:ReceivedBytesThreshold = 1

  //1、设置串口的属性
sp = new SerialPort(); sp.ReceivedBytesThreshold = ;//获取DataReceived事件发生前内部缓存区字节数
sp.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);//设置委托

    #3 点击“发送数据”按钮的事件如下:  

         /// <summary>
/// 【发送数据】
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
//发送串口数据 //1、检查串口设置
if (!CheckPortSetting())
{
MessageBox.Show("串口未设置!", "错误提示");
return;
} //2、检查发送数据是否为空
//if (!CheckSendData())
//{
// MessageBox.Show("请输入要发送的数据!", "错误提示");
// return;
//} //3、设置
if (!isSetProperty)
{
SetPortProperty();
isSetProperty = true;
} //4、写串口数据
if (isOpen)
{
//写出口数据
try
{
//sp.Write(tbxSendData.Text);
tbxStatus.Text = "发送成功!";
//tbxSendData.Text += tbxAddress.Text; byte address = Convert.ToByte( tbxAddress.Text.Trim(), );//地址码
byte cmd = Convert.ToByte(tbxCmd.Text.Trim(),);//命令帧
byte regAddr = Convert.ToByte(tbxRegAddr.Text.Trim(), );//寄存器地址
byte regNum = Convert.ToByte(tbxRegNum.Text.Trim(), );//寄存器数量 //Modbus相关处理对象
MyModbus modbus = new MyModbus();
byte[] text = modbus.GetReadFrame(address, cmd, regAddr, regNum, ); sp.Write(text, , );
tbxRecvData.Text += "Send:" + BitConverter.ToString(text)+ "\r\n"; }
catch
{
tbxStatus.Text = "发送数据错误";
}
}
else
{
MessageBox.Show("串口未打开", "错误提示");
} }

    

  2.7 附加代码

    #1 这里的MyModbus主要为Modbus相关一些操作,包括把发送数据封装成Modbus数据帧等。   

 using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace 串口调试
{
class MyModbus
{ #region CRC高位表 byte[] _auchCRCHi
private static readonly byte[] _auchCRCHi = new byte[]//crc高位表
{
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40,
0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1,
0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41,
0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0,
0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
};
#endregion #region CRC低位表 byte[] _auchCRCLo
private static readonly byte[] _auchCRCLo = new byte[]//crc低位表
{
0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2, 0xC6, 0x06,
0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04, 0xCC, 0x0C, 0x0D, 0xCD,
0x0F, 0xCF, 0xCE, 0x0E, 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09,
0x08, 0xC8, 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A,
0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC, 0x14, 0xD4,
0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6, 0xD2, 0x12, 0x13, 0xD3,
0x11, 0xD1, 0xD0, 0x10, 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3,
0xF2, 0x32, 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4,
0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE, 0xFA, 0x3A,
0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38, 0x28, 0xE8, 0xE9, 0x29,
0xEB, 0x2B, 0x2A, 0xEA, 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED,
0xEC, 0x2C, 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26,
0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0, 0xA0, 0x60,
0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62, 0x66, 0xA6, 0xA7, 0x67,
0xA5, 0x65, 0x64, 0xA4, 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F,
0x6E, 0xAE, 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68,
0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA, 0xBE, 0x7E,
0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C, 0xB4, 0x74, 0x75, 0xB5,
0x77, 0xB7, 0xB6, 0x76, 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71,
0x70, 0xB0, 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92,
0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54, 0x9C, 0x5C,
0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E, 0x5A, 0x9A, 0x9B, 0x5B,
0x99, 0x59, 0x58, 0x98, 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B,
0x8A, 0x4A, 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C,
0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86, 0x82, 0x42,
0x43, 0x83, 0x41, 0x81, 0x80, 0x40
};
#endregion /// <summary>
/// 【获取读数据命令,返回命令帧】
/// </summary>
/// <param name="mdaddr">地址码</param>
/// <param name="R_CMD">功能码</param>
/// <param name="min_reg">寄存器地址</param>
/// <param name="data_len">寄存器个数</param>
/// <param name="R_CMD_LEN">命令长度</param>
/// <returns></returns>
public byte[] GetReadFrame(byte mdaddr, byte R_CMD, ushort min_reg, ushort data_len, int R_CMD_LEN)
{
//主机命令帧格式
// 字节 功能描述 例子
//
// 1 地址码 0x01
// 2 功能码 0x03
// 3 寄存器地址高 0x00
// 4 寄存器地址低 0x00
// 5 寄存器个数高 0x00
// 6 寄存器个数低 0x02
// 7 CRC检验码低 0xC4
// 8 CRC校验码高 0x0B ushort crc;
byte[] message = new byte[]; //设置模块号
message[] = mdaddr;
//设置命令字
message[] = R_CMD; //设置开始寄存器
message[] = WORD_HI(min_reg);
message[] = WORD_LO(min_reg); //设置数据长度
message[] = WORD_HI(data_len);
message[] = WORD_LO(data_len); //设置 CRC
crc = CRC16(message, , R_CMD_LEN - ); message[] = WORD_HI(crc);//CRC校验码高位
message[] = WORD_LO(crc);//CRC校验码低位 return message;
} /// <summary>
/// 【格式化输出,校验读取的数据】
/// </summary>
/// <param name="readBuffer"></param>
/// <returns></returns>
public string SetText(byte[] readBuffer)
{
//将byte 转换成string 用于显示
//string readstr = string.Empty;
if (readBuffer != null)
{
ushort crc = CRC16(readBuffer, , readBuffer.Length - );
if (readBuffer[readBuffer.Length - ] == WORD_HI(crc) && readBuffer[readBuffer.Length - ] == WORD_LO(crc))//crc校验
{
return ToHexString(readBuffer);
}
else
{
return "CRC校验错误";
}
} return "程序出错";
} /// <summary>
/// 【CRC校验】
/// </summary>
/// <param name="buffer">命令帧合适前6字节</param>
/// <param name="Sset">开始位</param>
/// <param name="Eset">结束位</param>
/// <returns>CRC校验码</returns>
public static ushort CRC16(Byte[] buffer, int Sset, int Eset)
{
byte crcHi = 0xff; // 高位初始化 byte crcLo = 0xff; // 低位初始化 for (int i = Sset; i <= Eset; i++)
{
int crcIndex = crcHi ^ buffer[i]; //查找crc表值 crcHi = (byte)(crcLo ^ _auchCRCHi[crcIndex]);
crcLo = _auchCRCLo[crcIndex];
} return (ushort)(crcHi << | crcLo);
} /// <summary>
/// 【获取大写字母】
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string ToHexString(byte[] bytes) // 0xae00cf => "AE00CF "
{
string hexString = string.Empty; if (bytes != null)
{ StringBuilder strB = new StringBuilder(); for (int i = ; i < bytes.Length; i++)
{ strB.Append(bytes[i].ToString("X2")); } hexString = strB.ToString(); } return hexString; } //取Word变量的高位字节、低位字节
/// <summary>
/// 【获取低位字节】
/// </summary>
/// <param name="crcCLo"></param>
/// <returns></returns>
public static byte WORD_LO(ushort crcCLo)
{
crcCLo = (ushort)(crcCLo & 0X00FF);
return (byte)crcCLo;
} /// <summary>
/// 【获取高位字节】
/// </summary>
/// <param name="crcHI"></param>
/// <returns></returns>
public static byte WORD_HI(ushort crcHI)
{
crcHI = (ushort)(crcHI >> & 0X00FF);
return (byte)crcHI;
}
}
}

MyModbus.cs

    

    #2 下面为Form1.cs的代码,主要包括窗体一些基本操作。   

 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.Threading.Tasks;
using System.Windows.Forms; namespace 串口调试
{
public partial class Form1 : Form
{
SerialPort sp = null; bool isOpen = false;//是否打开 bool isSetProperty = false; //数据接收使用的代理
private delegate void myDelegate(byte[] readBuffer); public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{ //设置窗口大小固定
this.MaximumSize = this.Size;
this.MinimumSize = this.Size; //1、设置串口下拉列表
for ( int i = ; i < ; i++ )
{
cbxCOMPort.Items.Add("COM" + (i + ).ToString());
}
cbxCOMPort.SelectedIndex = ;//默认选项 //2、设置常用波特率
int bt = ;
for (int i = ; i < ; i++)
{
cbxBaudRate.Items.Add(bt.ToString());
bt *= ;
} cbxBaudRate.Items.Add("");
cbxBaudRate.Items.Add("");
cbxBaudRate.Items.Add("");
cbxBaudRate.Items.Add("");
cbxBaudRate.Items.Add("");
cbxBaudRate.SelectedIndex = ; //3、列出停止位
cbxStopBits.Items.Add("");
cbxStopBits.Items.Add("");
cbxStopBits.Items.Add("1.5");
cbxStopBits.Items.Add("");
cbxStopBits.SelectedIndex = ; //4、设置奇偶检验
cbxParity.Items.Add("无");
cbxParity.Items.Add("奇校验");
cbxParity.Items.Add("偶校验");
cbxParity.SelectedIndex = ; //5、设置数据位
cbxDataBits.Items.Add("");
cbxDataBits.Items.Add("");
cbxDataBits.Items.Add("");
cbxDataBits.Items.Add("");
cbxDataBits.SelectedIndex = ; } /// <summary>
/// 【串口检测按钮】
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCheckCOM_Click(object sender, EventArgs e)
{
//1、检测哪些端口可用
cbxCOMPort.Items.Clear();
cbxCOMPort.Text = ""; lblStatus.Text = "执行中...";
string str = "";
for (int i = ; i < ; i++)
{
try
{
SerialPort sp = new SerialPort("COM" + (i + ).ToString());
sp.Open();
sp.Close();
cbxCOMPort.Items.Add("COM" + (i + ).ToString());
}
catch
{
str += "COM" + (i + ).ToString() + "、";
continue;
}
} if(cbxCOMPort.Items.Count > )
cbxCOMPort.SelectedIndex = ;
lblStatus.Text = "完成";
tbxStatus.Text = str;
} public void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
myDelegate md = new myDelegate(ShowRst);
try
{
if (sp.IsOpen)
{
int count = sp.BytesToRead;
if (count > )
{
byte[] readBuffer = new byte[count];
sp.Read(readBuffer, , count);//读取串口数据
// serialPort1.Write(readBuffer, 0, count);
Invoke(md, readBuffer);
}
}
}
catch (Exception err)
{
throw err;
} } /// <summary>
/// 【显示接收返回的数据】
/// </summary>
/// <param name="resbuffer"></param>
public void ShowRst(byte[] resbuffer)
{
MyModbus modbus = new MyModbus();
tbxRecvData.Text += "Recv:" + modbus.SetText(resbuffer) + "\r\n";
tbxRecvData.Text += "\r\n";
} /// <summary>
/// 【检测端口设置】
/// </summary>
/// <returns></returns>
private bool CheckPortSetting()
{
//检测端口设置
if (cbxCOMPort.Text.Trim() == "" || cbxBaudRate.Text.Trim() == "" || cbxStopBits.Text.Trim() == "" || cbxParity.Text.Trim() == "" || cbxDataBits.Text.Trim() == "")
return false;
return true;
} /// <summary>
/// 【检测发送数据是否为空】
/// </summary>
/// <returns></returns>
private bool CheckSendData()
{
if (tbxSendData.Text.Trim() == "")
return false;
return true;
} /// <summary>
/// 【设置串口属性】
/// </summary>
private void SetPortProperty()
{
//1、设置串口的属性
sp = new SerialPort(); sp.ReceivedBytesThreshold = ;//获取DataReceived事件发生前内部缓存区字节数
sp.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);//设置委托 sp.PortName = cbxCOMPort.Text.Trim(); //2、设置波特率
sp.BaudRate = Convert.ToInt32( cbxBaudRate.Text.Trim()); //3、设置停止位
float f = Convert.ToSingle( cbxStopBits.Text.Trim()); if (f == )
{
sp.StopBits = StopBits.None;//表示不使用停止位
}
else if (f == 1.5)
{
sp.StopBits = StopBits.OnePointFive;//使用1.5个停止位
}
else if (f == )
{
sp.StopBits = StopBits.Two;//表示使用两个停止位
}
else
{
sp.StopBits = StopBits.One;//默认使用一个停止位
} //4、设置数据位
sp.DataBits = Convert.ToInt16(cbxDataBits.Text.Trim()); //5、设置奇偶校验位
string s = cbxParity.Text.Trim();
if (s.CompareTo("无") == )
{
sp.Parity = Parity.None;//不发生奇偶校验检查
}
else if (s.CompareTo("奇校验") == )
{
sp.Parity = Parity.Odd;//设置奇校验
}
else if (s.CompareTo("偶校验") == )
{
sp.Parity = Parity.Even;//设置偶检验
}
else
{
sp.Parity = Parity.None;
} //6、设置超时读取时间
sp.ReadTimeout = -; //7、打开串口
try
{
sp.Open();
isOpen = true;
}
catch(Exception)
{
lblStatus.Text = "打开串口错误!";
} } /// <summary>
/// 【发送数据】
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
//发送串口数据 //1、检查串口设置
if (!CheckPortSetting())
{
MessageBox.Show("串口未设置!", "错误提示");
return;
} //2、检查发送数据是否为空
//if (!CheckSendData())
//{
// MessageBox.Show("请输入要发送的数据!", "错误提示");
// return;
//} //3、设置
if (!isSetProperty)
{
SetPortProperty();
isSetProperty = true;
} //4、写串口数据
if (isOpen)
{
//写出口数据
try
{
//sp.Write(tbxSendData.Text);
tbxStatus.Text = "发送成功!";
//tbxSendData.Text += tbxAddress.Text; byte address = Convert.ToByte( tbxAddress.Text.Trim(), );//地址码
byte cmd = Convert.ToByte(tbxCmd.Text.Trim(),);//命令帧
byte regAddr = Convert.ToByte(tbxRegAddr.Text.Trim(), );//寄存器地址
byte regNum = Convert.ToByte(tbxRegNum.Text.Trim(), );//寄存器数量 //Modbus相关处理对象
MyModbus modbus = new MyModbus();
byte[] text = modbus.GetReadFrame(address, cmd, regAddr, regNum, ); sp.Write(text, , );
tbxRecvData.Text += "Send:" + BitConverter.ToString(text)+ "\r\n"; }
catch
{
tbxStatus.Text = "发送数据错误";
}
}
else
{
MessageBox.Show("串口未打开", "错误提示");
} } /// <summary>
/// 【读取数据】
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRecv_Click(object sender, EventArgs e)
{
if(isOpen) 
            { 
try 
                {
//读取串口数据
 
                    tbxRecvData.Text += sp.ReadLine()+"\r\n"; 
                } 
                catch(Exception) 
                { 
                    lblStatus.Text = "读取串口时发生错误!"; 
                    return; 
                } 
            } 
            else 
            { 
              MessageBox.Show("串口未打开!", "错误提示"); 
              return;              } 
} }
}

Form1.cs

 三、最后说一句

  由于需要查询大量资料,有些代码是引用别人的,所以这里要感谢那些分享的人,秉着分享精神,希望可以帮助更多的人。

  如果发现有什么错误,或者建议,请留言,谢谢!

上一篇:C++科学计算库GSL及其配置


下一篇:【数据仓库】数据漂移的处理