C#编程之c#串口通信讲解(一)(winform、wpf)
小标 2018-12-28 来源 : 阅读 3125 评论 0

摘要:本文主要向大家介绍了C#编程之c#串口通信讲解(一)(winform、wpf),通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

本文主要向大家介绍了C#编程之c#串口通信讲解(一)(winform、wpf),通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

串口操作需要注意的几点如下:
1、如果是USB转串口;则需要安装USB转串口驱动,附件有此驱动。
2、串口打开状态最好不要直接插拔串口,可能会导致中控板或者串口线烧坏。
3、使用串口调试工具CEIWEI,下一章节会贴上使用教程
简单的串口收发通信,有以下步骤:
1、打开制定的串口、绑定串口接收事件
2、初始化串口指令
3、发送串口指令
 
-------打开串口代码--------

/// 


        /// 打开串口
        /// 


        /// 

串口号
        /// 

波特率
        /// 

数据位
        /// 

停止位
        /// /// 

校验位
        /// 


        public bool OpenSerial(string strPortName, int nRate, int nDataBit, float nStopBits, int nParity)
        {
            //这里就是绑定串口接收回调事件,即发送一条串口命令,发送成功,则会触发此事件进入ReciceSerialData方法,我们就进行判断发送成功还是失败。
            serial.DataReceived += new SerialDataReceivedEventHandler(ReciveSerialData);
            serial.PortName = strPortName;//串口号
            serial.BaudRate = nRate;//波特率
            float f = nStopBits;//停止位
            if (f == 0)
            {
                serial.StopBits = StopBits.None;
            }
            else if (f == 1.5)
            {
                serial.StopBits = StopBits.OnePointFive;
            }
            else if (f == 1)
            {
                serial.StopBits = StopBits.One;
            }
            else
            {
                serial.StopBits = StopBits.Two;
            }

            serial.DataBits = nDataBit;//数据位
            if (nParity == 0) //校验位
            {
                serial.Parity = Parity.None;
            }
            else if (nParity == 1)
            {
                serial.Parity = Parity.Odd;
            }
            else if (nParity == 2)
            {
                serial.Parity = Parity.Even;
            }
            else
            {
                serial.Parity = Parity.None;
            }

            serial.ReadTimeout = 3000;//设置超时读取时间
            serial.WriteTimeout = 500;//超时写入时间
            try
            {
                if (!serial.IsOpen)
                {
                    serial.Open();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }

            return true;

        }


 -------使用实例--------

//定义串口对象
private SerialPort serial = new SerialPort();

//在按钮Click事件里调用打开串口的方法,串口COM号参数以本机具体串口号为准,COM1除外,如果只有COM1则需要安装串口驱动,见附件
private void btnOpenSerial_Click(object sender, EventArgs e)
        {
            if (!OpenSerial("COM3", 115200, 8, 1, 0))
            {
                //串口打开失败
                MessageBox.Show("串口打开失败!");
            }
        }


-------初始化串口命令、发送指令-------
注:我这个命令并不是通用的,是根据我这边的中控板协议;发对应的命令,但是其他中控板的命令格式也是差不多的

   /// 


       /// 初始化串口命令
       /// 


       /// 

操作类型
        public void InitialSerialCommand(int nStaus)
        {
            byte[] btyData = new byte[100];
            btyData[0] = 0x5A;
            btyData[1] = 0x55;
            btyData[2] = 0x00;
            btyData[3] = 0x00;
            btyData[4] = 0x02;
            btyData[5] = 0xD1;
            btyData[6] = 0x00;
            btyData[7] = 0x18;
            btyData[8] = 0x6A;
            btyData[9] = 0x69;

            //开灯
            if (nStaus == 0)
            {
                btyData[6] = 0x01;
            }
            //全关
            else 
            {
                btyData[6] = 0x00;
            }
           
            //发送指令
            if (serial != null)
            {
                try
                {
                    SerialWrite(0, btyData);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }


---------串口回调方法-----------

        /// 


        /// 接收数据事件
        /// 


        /// 


        /// 


        private void ReciveSerialData(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                if (serial.BytesToRead == 0)
                {
                    return;
                }
                byte[] btyReciveData = new byte[serial.BytesToRead];
                byte[] btyResoureData = new byte[btyReciveData.Length];
                string strData = string.Empty;
                int intSp = serial.Read(btyReciveData, 0, btyReciveData.Length);//在此就可以读取到当前缓冲区内的数据
                int i = 0;
                string[] hex = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
                for (i = 0; i < btyReciveData.Length; i++)
                {
                    btyResoureData[i] = Convert.ToByte(("0x" + (hex[btyReciveData[i] / 16]).ToString() + (hex[btyReciveData[i] % 16]).ToString()), 16);
                }
                for (int a = 0; a < btyReciveData.Length; a++)
                {
                    strData += btyResoureData[a].ToString("X2");
                }

                //若串口命令发送成功,则会返回和发送指令一样的指令,我发送的指令是(5A55000002D101186A69 );返回的也是(5A55000002D101186A69 );则可以判定串口数据交互成功。
                if (strData.IndexOf("5A55000002D101186A69") >= 0)
                {      
                    //发送成功
                }                    
                                     
                                     
                                     
            }                        
            catch (Exception ex)     
            {
                MessageBox.Show(ex.ToString());
            }
        }

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 0 不喜欢 | 0
看完这篇文章有何感觉?已经有0人表态,0%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程