c#实现串口通信

标签: c# 串口通信
7人阅读 评论(0) 收藏 举报
分类:
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 test
{
    public partial class Form1 : Form
    {
        private SerialPort ComDevice = new SerialPort();

        public Form1()
        {
            InitializeComponent();
            init();
        }


        /// <summary>
        /// 初始化端口
        /// </summary>
        public void init()
        {

            btnSend.Enabled = false;
            cmbPort.Items.AddRange(SerialPort.GetPortNames());
            if (cmbPort.Items.Count > 0)
            {
                cmbPort.SelectedIndex = 0;
            }
             //波特率
            cmbBaudRate.Items.Add("110");
            cmbBaudRate.Items.Add("300");
            cmbBaudRate.Items.Add("1200");
            cmbBaudRate.Items.Add("2400");
            cmbBaudRate.Items.Add("4800");
            cmbBaudRate.Items.Add("9600");
            cmbBaudRate.Items.Add("19200");
            cmbBaudRate.Items.Add("38400");
            cmbBaudRate.Items.Add("57600");
            cmbBaudRate.Items.Add("115200");
            cmbBaudRate.Items.Add("230400");
            cmbBaudRate.Items.Add("460800");
            cmbBaudRate.Items.Add("921600");
            cmbBaudRate.SelectedIndex = 5;

            //数据位
            cmbDataBits.Items.Add("5");
            cmbDataBits.Items.Add("6");
            cmbDataBits.Items.Add("7");
            cmbDataBits.Items.Add("8");
            cmbDataBits.SelectedIndex = 3;

            //停止位
            cmbStopBit.Items.Add("1");
            cmbStopBit.SelectedIndex = 0;

            //佼验位
            cmbParity.Items.Add("无");
            cmbParity.SelectedIndex = 0;

            ComDevice.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);//绑定事件

        }

        private void radioButton3_CheckedChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 打开串口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpen_Click(object sender, EventArgs e)
        {

  
            if (cmbPort.Items.Count <= 0)
            {
                MessageBox.Show("没有发现串口,请检查线路!");
                return;
            }
            if (ComDevice.IsOpen == false)
            {
                ComDevice.PortName = cmbPort.SelectedItem.ToString();
                ComDevice.BaudRate = Convert.ToInt32(cmbBaudRate.SelectedItem.ToString());
                ComDevice.Parity = (Parity)Convert.ToInt32(cmbParity.SelectedIndex.ToString());
                ComDevice.DataBits = Convert.ToInt32(cmbDataBits.SelectedItem.ToString());
                ComDevice.StopBits = (StopBits)Convert.ToInt32(cmbStopBit.SelectedItem.ToString());
                try
                {
                    ComDevice.Open();
                    btnSend.Enabled = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                btnOpen.Text = "关闭串口";
            }else{
                try
                {
                    ComDevice.Close();
                    btnSend.Enabled = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                btnOpen.Text = "打开串口";
            }
            cmbPort.Enabled = !ComDevice.IsOpen;
            cmbBaudRate.Enabled = !ComDevice.IsOpen;
            cmbParity.Enabled = !ComDevice.IsOpen;
            cmbDataBits.Enabled = !ComDevice.IsOpen;
            cmbStopBit.Enabled = !ComDevice.IsOpen;
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public bool SendData(byte[] data) {
            if (ComDevice.IsOpen)
            {
                try
                {
                    ComDevice.Write(data, 0, data.Length);//发送数据
                    ComDevice.Write(txtSendData.Text);
                    return true;
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else {
                MessageBox.Show("串口未打开", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return false;
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
         private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e){
             if (ComDevice.IsOpen)
             {
                 byte[] ReDatas = new byte[ComDevice.BytesToRead];
                 ComDevice.Read(ReDatas, 0, ReDatas.Length);//读取数据
                 this.AddData(ReDatas);//输出数据
             }
             else {
                 MessageBox.Show("请先打开串口");
             }
           
        }

        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="data"></param>
         public void AddData(byte[] data)
         {
             if (radioButton1.Checked)
             {
                 StringBuilder sb = new StringBuilder();
                 for (int i = 0; i < data.Length; i++)
                 {
                     sb.AppendFormat("{0:x2}" + " ", data[i]);
                 }
                 AddContent(sb.ToString().ToUpper());
             }
             else if (radioButton4.Checked)
             {
                 AddContent(new ASCIIEncoding().GetString(data));
             }
             else if (radioButton3.Checked)
             {
                 AddContent(new UTF8Encoding().GetString(data));
             }
             else if (radioButton2.Checked)
             {
                 AddContent(new UnicodeEncoding().GetString(data));
             }
             else
             { }

             lblRevCount.Invoke(new MethodInvoker(delegate
             {
                 lblRevCount.Text = (int.Parse(lblRevCount.Text) + data.Length).ToString();
             }));
         }


        /// <summary>
        /// 输入到显示区域
        /// </summary>
        /// <param name="content"></param>
         private void AddContent(string content)
         {
             this.BeginInvoke(new MethodInvoker(delegate
             {
                 if (chkAutoLine.Checked && txtShowData.Text.Length > 0)
                 {
                     txtShowData.AppendText("\r\n");
                 }
                 txtShowData.AppendText(content);
             }));
         }
        /// <summary>
        /// 发送button事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] sendData = null;
            if(rbtnSendHex.Checked){
                sendData = strToHexByte(txtSendData.Text.Trim());
            }else if(rbtnSendASCII.Checked){
                sendData = Encoding.ASCII.GetBytes(txtSendData.Text.Trim());
            }else if(rbtnSendUTF8.Checked){
                sendData = Encoding.UTF8.GetBytes(txtSendData.Text.Trim());
            }
            else if (rbtnSendUnicode.Checked)
            {
                sendData = Encoding.Unicode.GetBytes(txtSendData.Text.Trim());
            }
            else {
                sendData = Encoding.ASCII.GetBytes(txtSendData.Text.Trim());
            }


            if (this.SendData(sendData))
            {
                lblSendCount.Invoke(new MethodInvoker(delegate
                {
                    lblSendCount.Text = (int.Parse(lblSendCount.Text) + txtSendData.Text.Length).ToString();
                }));

            }
            else { 
                
            }
        }

        /// <summary>
        /// 字符串转换16进制字节数组
        /// </summary>
        /// <param name="hexString"></param>
        /// <returns></returns>
        private byte[] strToHexByte(string hexString)
        {
            hexString = hexString.Replace(" ", "");
            if ((hexString.Length % 2) != 0)
                hexString += " ";
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
                returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2).Replace(" ", ""), 16);
            return returnBytes;
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }

        /// <summary>
        /// 清空接收区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClearRev_Click(object sender, EventArgs e)
        {
            txtShowData.Clear();
        }

        /// <summary>
        /// 清空发送区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClearSend_Click(object sender, EventArgs e)
        {
            txtSendData.Clear();
        }   
    }
}

visual studio程序打包发布的方法

点击打开链接

源代码(内附打包所需InstallShield)

点击打开链接


查看评论

用C#一步步写串口通信

用C#一步步写串口通信 标签: c#textboxbuttonobjectstring 2012-08-10 14:57 18916人阅读 评论(38) 收藏 举报  分类:...
  • kasama1953
  • kasama1953
  • 2016-05-17 10:43:35
  • 63695

C#串口通信

本文主要是讲述如何通过C# .net1.1平台调用API操作串口,.net2.0已经内置串口操作类! 通常,在C#中实现串口通信,我们有四种方法: 第一:通过MSCOMM控件这是最简单的,最方便的方法...
  • byxdaz
  • byxdaz
  • 2011-09-04 23:40:28
  • 31687

C#实现串口通信(自身留稿方便以后查看)

串口通信
  • u011549779
  • u011549779
  • 2016-08-01 11:19:04
  • 1141

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

  • 2017年04月26日 18:20
  • 162KB
  • 下载

在C#中实现串口通信的方法

通常,在C#中实现串口通信,我们有四种方法: 第一:通过MSCOMM控件这是最简单的,最方便的方法。可功能上很难做到控制自如,同时这个控件并不是系统本身所带,所以还得注册,不在本文讨论范围。可以访问h...
  • smartsmile2012
  • smartsmile2012
  • 2014-04-22 17:28:35
  • 2946

C#串口通信工具

  • 2012年09月08日 09:57
  • 70KB
  • 下载

c#编写串口通讯代码 多线程实现

  • 2015年12月31日 12:55
  • 255KB
  • 下载

C#串口通讯实例

C#串口通讯实例 参考《C#网络通信程序设计》 serialport
  • song430
  • song430
  • 2016-12-19 20:27:18
  • 1099

C#初入串口通信(串行通信)总结

使用WinFrom来实现: 首先要知道串口通信协议以及原理 原理大概提一下:要自己翻阅看。(http://book.51cto.com/art/200911/162532.htm或者http://...
  • xujunheng
  • xujunheng
  • 2014-09-09 19:07:40
  • 11050

基于VS2013 C# 多串口通讯演示源代码

  • 2017年10月07日 16:17
  • 69KB
  • 下载
    个人资料
    持之以恒
    等级:
    访问量: 1814
    积分: 165
    排名: 107万+
    文章分类