zoukankan      html  css  js  c++  java
  • C#串口介绍以及简单串口通信程序设计实现

    C#串口介绍以及简单串口通信程序设计实现

    周末,没事干,写个简单的串口通信工具,也算是本周末曾来过,废话不多,直接到主题

    串口介绍

      串行接口简称串口,也称串行通信接口或串行通讯接口(通常指COM接口),是采用串行通信方式的扩展接口。(至于再详细,自己百度)

    串口应用:

      工业领域使用较多,比如:数据采集,设备控制等等,好多都是用串口通信来实现!你要是细心的话,你会发现,目前家用国网智能电能表就具备RS485通信总线(串行总线的一种)与RS232可以相互转化(当然一般,非专业的谁也不会闲的蛋疼,趴电表上瞎看,最多也就看看走了多少度电)

    RS232 DB9介绍:

    1.示意图

    2.针脚介绍:

    1.  载波检测(DCD) 
    2.  接受数据(RXD) 
    3.  发出数据(TXD) 
    4.  数据终端准备好(DTR) 
    5.  信号地线(SG)
    6.  数据准备好(DSR)
    7.  请求发送(RTS)
    8.  清除发送(CTS)
    9.  振铃指示(RI)

    3.实物图:

    以下是我购买XX公司的一个usb转串口线:这个头就是一个公头,另一端是一个usb口

    笨小孩串口工具运行图:

    1.开启程序

    2.发送一行字符串HelloBenXH,直接将针脚的发送和接收链接起来就可以测试了(针脚2 接受数据(RXD) 和3 发出数据(TXD))直接链接,

    C#代码实现:采用SerialPort

    1.实例化一个SerialPort

    1 private SerialPort ComDevice = new SerialPort();

    2.初始化参数绑定接收数据事件

    复制代码
     1 public void init()
     2         {
     3             btnSend.Enabled = false;
     4             cbbComList.Items.AddRange(SerialPort.GetPortNames());
     5             if (cbbComList.Items.Count > 0)
     6             {
     7                 cbbComList.SelectedIndex = 0;
     8             }
     9             cbbBaudRate.SelectedIndex = 5;
    10             cbbDataBits.SelectedIndex = 0;
    11             cbbParity.SelectedIndex = 0; 
    12             cbbStopBits.SelectedIndex = 0;
    13             pictureBox1.BackgroundImage = Properties.Resources.red;
    14 
    15             ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);//绑定事件
    16             
    17         }
    复制代码

    3.打开串口button事件

    复制代码
     1 /// <summary>
     2         /// 打开串口
     3         /// </summary>
     4         /// <param name="sender"></param>
     5         /// <param name="e"></param>
     6         private void btnOpen_Click(object sender, EventArgs e)
     7         {
     8             if (cbbComList.Items.Count <= 0)
     9             {
    10                 MessageBox.Show("没有发现串口,请检查线路!");
    11                 return;
    12             }
    13 
    14             if (ComDevice.IsOpen == false)
    15             {
    16                 ComDevice.PortName = cbbComList.SelectedItem.ToString();
    17                 ComDevice.BaudRate = Convert.ToInt32(cbbBaudRate.SelectedItem.ToString());
    18                 ComDevice.Parity = (Parity)Convert.ToInt32(cbbParity.SelectedIndex.ToString());
    19                 ComDevice.DataBits = Convert.ToInt32(cbbDataBits.SelectedItem.ToString());
    20                 ComDevice.StopBits = (StopBits)Convert.ToInt32(cbbStopBits.SelectedItem.ToString());
    21                 try
    22                 {
    23                     ComDevice.Open();
    24                     btnSend.Enabled = true;
    25                 }
    26                 catch (Exception ex)
    27                 {
    28                     MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
    29                     return;
    30                 }
    31                 btnOpen.Text = "关闭串口";
    32                 pictureBox1.BackgroundImage = Properties.Resources.green;
    33             }
    34             else
    35             {
    36                 try
    37                 {
    38                     ComDevice.Close();
    39                     btnSend.Enabled = false;
    40                 }
    41                 catch (Exception ex)
    42                 {
    43                     MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
    44                 }
    45                 btnOpen.Text = "打开串口";
    46                 pictureBox1.BackgroundImage = Properties.Resources.red;
    47             }
    48 
    49             cbbComList.Enabled = !ComDevice.IsOpen;
    50             cbbBaudRate.Enabled = !ComDevice.IsOpen;
    51             cbbParity.Enabled = !ComDevice.IsOpen;
    52             cbbDataBits.Enabled = !ComDevice.IsOpen;
    53             cbbStopBits.Enabled = !ComDevice.IsOpen;
    54         }
    复制代码

    4.发送数据

    复制代码
     1 /// <summary>
     2         /// 发送数据
     3         /// </summary>
     4         /// <param name="sender"></param>
     5         /// <param name="data"></param>
     6         public bool SendData(byte[] data)
     7         {
     8             if (ComDevice.IsOpen)
     9             {
    10                 try
    11                 {
    12                     ComDevice.Write(data, 0, data.Length);//发送数据
    13                     return true;
    14                 }
    15                 catch (Exception ex)
    16                 {
    17                     MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
    18                 }
    19             }
    20             else
    21             {
    22                 MessageBox.Show("串口未打开", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
    23             }
    24             return false;
    25         }
    26 
    27         /// <summary>
    28         /// 发送数据button事件
    29         /// </summary>
    30         /// <param name="sender"></param>
    31         /// <param name="e"></param>
    32         private void btnSend_Click(object sender, EventArgs e)
    33         {
    34             byte[] sendData = null;
    35 
    36             if (rbtnSendHex.Checked)
    37             {
    38                 sendData = strToHexByte(txtSendData.Text.Trim());
    39             }
    40             else if (rbtnSendASCII.Checked)
    41             {
    42                 sendData = Encoding.ASCII.GetBytes(txtSendData.Text.Trim());
    43             }
    44             else if (rbtnSendUTF8.Checked)
    45             {
    46                 sendData = Encoding.UTF8.GetBytes(txtSendData.Text.Trim());
    47             }
    48             else if (rbtnSendUnicode.Checked)
    49             {
    50                 sendData = Encoding.Unicode.GetBytes(txtSendData.Text.Trim());
    51             }
    52             else
    53             {
    54                 sendData = Encoding.ASCII.GetBytes(txtSendData.Text.Trim());
    55             }
    56 
    57             if (this.SendData(sendData))//发送数据成功计数
    58             {
    59                 lblSendCount.Invoke(new MethodInvoker(delegate
    60                 {
    61                     lblSendCount.Text = (int.Parse(lblSendCount.Text) + txtSendData.Text.Length).ToString();
    62                 }));
    63             }
    64             else
    65             {
    66 
    67             }
    68 
    69         }
    70 
    71         /// <summary>
    72         /// 字符串转换16进制字节数组
    73         /// </summary>
    74         /// <param name="hexString"></param>
    75         /// <returns></returns>
    76         private byte[] strToHexByte(string hexString)
    77         {
    78             hexString = hexString.Replace(" ", "");
    79             if ((hexString.Length % 2) != 0)
    80                 hexString += " ";
    81             byte[] returnBytes = new byte[hexString.Length / 2];
    82             for (int i = 0; i < returnBytes.Length; i++)
    83                 returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ",""), 16);
    84             return returnBytes;
    85         }
    复制代码

    5.接收和数据输出

    复制代码
     1 /// <summary>
     2         /// 接收数据
     3         /// </summary>
     4         /// <param name="sender"></param>
     5         /// <param name="e"></param>
     6         private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
     7         {
     8             byte[] ReDatas = new byte[ComDevice.BytesToRead];
     9             ComDevice.Read(ReDatas, 0, ReDatas.Length);//读取数据
    10             this.AddData(ReDatas);//输出数据
    11         }
    12        
    13         /// <summary>
    14         /// 添加数据
    15         /// </summary>
    16         /// <param name="data">字节数组</param>
    17         public void AddData(byte[] data)
    18         {
    19             if (rbtnHex.Checked)
    20             {
    21                 StringBuilder sb = new StringBuilder();
    22                 for (int i = 0; i < data.Length; i++)
    23                 {
    24                     sb.AppendFormat("{0:x2}" + " ", data[i]);
    25                 }
    26                 AddContent(sb.ToString().ToUpper());
    27             }
    28             else if (rbtnASCII.Checked)
    29             {
    30                 AddContent(new ASCIIEncoding().GetString(data));
    31             }
    32             else if (rbtnUTF8.Checked)
    33             {
    34                 AddContent(new UTF8Encoding().GetString(data));
    35             }
    36             else if (rbtnUnicode.Checked)
    37             {
    38                 AddContent(new UnicodeEncoding().GetString(data));
    39             }
    40             else
    41             {}
    42           
    43             lblRevCount.Invoke(new MethodInvoker(delegate
    44             {
    45                 lblRevCount.Text = (int.Parse(lblRevCount.Text) + data.Length).ToString();
    46             }));
    47         }
    48 
    49 
    50         /// <summary>
    51         /// 输入到显示区域
    52         /// </summary>
    53         /// <param name="content"></param>
    54         private void AddContent(string content)
    55         {
    56             this.BeginInvoke(new MethodInvoker(delegate
    57             {
    58                 if(chkAutoLine.Checked && txtShowData.Text.Length>0)
    59                 {
    60                     txtShowData.AppendText("
    ");
    61                 }
    62                 txtShowData.AppendText(content);
    63             }));
    64         }
    复制代码

    6.清空数据区域事件

    复制代码
     1 /// <summary>
     2         /// 清空接收区
     3         /// </summary>
     4         /// <param name="sender"></param>
     5         /// <param name="e"></param>
     6         private void btnClearRev_Click(object sender, EventArgs e)
     7         {
     8             txtShowData.Clear();
     9         }
    10 
    11         /// <summary>
    12         /// 清空发送区
    13         /// </summary>
    14         /// <param name="sender"></param>
    15         /// <param name="e"></param>
    16         private void btnClearSend_Click(object sender, EventArgs e)
    17         {
    18             txtSendData.Clear();
    19         }
    复制代码

     运行程序下载地址  BXHSerialPort.exe

    源代码工程文件下载

  • 相关阅读:
    AngularJS开发指南6:AngularJS表单详解
    AngularJS开发指南5:AngularJS表达式详解
    AngularJS开发指南4:指令的详解
    grunt入门讲解7:项目脚手架grunt-init
    grunt入门讲解6:grunt使用步骤和总结
    grunt入门讲解5:创建插件,安装Grunt以及常见问题
    grunt入门讲解4:如何创建task(任务)
    grunt入门讲解3:实例讲解使用 Gruntfile 配置任务
    grunt入门讲解2:如何使用 Gruntfile 配置任务
    grunt入门讲解1:grunt的基本概念和使用
  • 原文地址:https://www.cnblogs.com/zxtceq/p/8780421.html
Copyright © 2011-2022 走看看