开发者论坛

 找回密码
 注册 (请使用非IE浏览器)
查看: 2658|回复: 1

[求助] C#串口接收数据会多回车换行符怎么处理?求助

[复制链接]

0

精华

10

贡献

127

赞扬

帖子
21
软币
262
在线时间
20 小时
注册时间
2021-6-7
发表于 2021-7-15 17:17:08 | 显示全部楼层 |阅读模式
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.IO;


namespace ComTool
{
    /*---------------作者:叶知秋----------------------*/
    /*---------------时间:2012年12月6日---------------*/
    /*---------------邮箱:yq@yyzq.net---------*/
    /*---------------www.yyzq.net--------------------------*/
    /*本人兼职各类软硬件系统集成,RFID系统集成,工控测试系统开发。*/
    /*任何个人均可免费修改,使用本程序,但请保留以上作者信息,谢谢!*/

    public partial class Form1 : Form
    {
        SerialPort ComDevice = new SerialPort();
        bool AllowReceive = true;
        SubWin.CheckWin Cwin = new SubWin.CheckWin();
        SubWin.ByteCaculator BCWin = new SubWin.ByteCaculator();
        Config cConfig;
        Config g_Config;
        string nowtime;
        string serialdata;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            lblVersion.Text += AssemblyLib.AssemblyVersion;
            //获取可用串口列表
            string[] ports = SerialPort.GetPortNames();
            foreach (string port in ports)
            {
                drpComList.Items.Add(port);
            }
            if (drpComList.Items.Count > 0)
            {
                drpComList.SelectedIndex = 0;
                btnCom.Enabled = true;
            }
            drpBaudRate.SelectedIndex = 11;
            drpParity.SelectedIndex = 0;
            drpDataBits.SelectedIndex = 0;
            drpStopBits.SelectedIndex = 0;
            ComDevice.DataReceived += new SerialDataReceivedEventHandler(ComDevice_DataReceived);
        }

        private void btnCom_Click(object sender, EventArgs e)
        {
            if (btnCom.Tag.ToString() == "0")
            {
                ComDevice.PortName = drpComList.SelectedItem.ToString();
                ComDevice.BaudRate = Convert.ToInt32(drpBaudRate.SelectedItem.ToString());
                ComDevice.Parity = (Parity)Convert.ToInt32(drpParity.SelectedIndex.ToString());
                ComDevice.DataBits = Convert.ToInt32(drpDataBits.SelectedItem.ToString());
                ComDevice.StopBits = (StopBits)Convert.ToInt32(drpStopBits.SelectedItem.ToString());
                try
                {
                    ComDevice.Open();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                btnCom.Text = "关闭串口";
                btnCom.Tag = "1";
                picComStatus.BackgroundImage = Properties.Resources.greenlight;
            }
            else
            {
                try
                {
                    ComDevice.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                btnCom.Text = "打开串口";
                btnCom.Tag = "0";
                picComStatus.BackgroundImage = Properties.Resources.redlight;
            }
        }

        #region 发送数据
        private void btnSend_Click(object sender, EventArgs e)
        {
            Send();
            if (cbxAutoSend.Checked == true)
            { //自动循环发送
                timerAutoSend.Interval = txtSendDelay.GetInt32Value();
                timerAutoSend.Enabled = true;
            }
            else
            {
                timerAutoSend.Enabled = false;
            }
        }

        private void timerAutoSend_Tick(object sender, EventArgs e)
        {
            Send();
        }

        private void cbxAutoSend_CheckedChanged(object sender, EventArgs e)
        {
            if (cbxAutoSend.Checked == false)
            {
                timerAutoSend.Enabled = false;
            }
        }
        //清空发送区
        private void btnClearS_Click(object sender, EventArgs e)
        {
            txtSend.Text = "";
        }

        /// <summary>
        /// 发送数据
        /// </summary>
        private void Send()
        {
            if (txtSend.Text.Length > 0)
            {
                if (ComDevice.IsOpen == true)
                {
                    byte[] SendBytes = null;
                    string SendData = txtSend.Text;
                    if (cbxHexS.Checked == true)
                    { //16进制发送
                        try
                        {
                            //剔除所有空格
                            SendData = SendData.Replace(" ", "");
                            if (SendData.Length % 2 == 1)
                            {//奇数个字符
                                SendData = SendData.Remove(SendData.Length - 1, 1);//去除末位字符
                            }
                            List<string> SendDataList = new List<string>();
                            for (int i = 0; i < SendData.Length; i = i + 2)
                            {
                                SendDataList.Add(SendData.Substring(i, 2));
                            }
                            SendBytes = new byte[SendDataList.Count];
                            for (int j = 0; j < SendBytes.Length; j++)
                            {
                                SendBytes[j] = (byte)(Convert.ToInt32(SendDataList[j], 16));
                            }
                        }
                        catch
                        {
                            timerAutoSend.Enabled = false;
                            MessageBox.Show("请输入正确的16进制数据!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        SendBytes = System.Text.Encoding.Default.GetBytes(SendData);
                    }
                    ComDevice.Write(SendBytes, 0, SendBytes.Length);//发送数据
                    lblSCount.Text = (Convert.ToInt32(lblSCount.Text) + SendBytes.Length).ToString();
                }
                else
                {
                    timerAutoSend.Enabled = false;
                    MessageBox.Show("请打开串口!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                timerAutoSend.Enabled = false;
                MessageBox.Show("请输入要发送的数据!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region 接收数据
        private void cbxAllowR_CheckedChanged(object sender, EventArgs e)
        {
            AllowReceive = cbxAllowR.Checked;
        }

        private void ComDevice_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
             byte[] ReDatas = new byte[ComDevice.BytesToRead];//返回命令包
            ComDevice.Read(ReDatas, 0, ReDatas.Length);//读取数据
             //txtReceive.Text = "";                                               
            if (AllowReceive == true)
            {



                if (cbxHexR.Checked == true)
                { //16进制显示
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < ReDatas.Length; i++)
                    {
                        sb.AppendFormat("{0:x2}" + " ", ReDatas);
                    }
                    UpdateRecevie(sb.ToString().ToUpper());
                }
                else
                {

                    string str = System.Text.Encoding.Default.GetString(ReDatas);
                    UpdateRecevie(System.Text.Encoding.Default.GetString(ReDatas));      
                    StreamWriter sw = new StreamWriter("F:\\TestTxt.txt", true);
                    sw.WriteLine(str);
                    sw.Close();



                }


                UpdateReceiveCount(ReDatas.Length);
            }
            else
            {
                ComDevice.DiscardInBuffer();

            }

        }
        //清空接收区
        private void btnClearR_Click(object sender, EventArgs e)
        {
            txtReceive.Text = string.Empty;
            textBox1.Text = string.Empty;
            textBox2.Text = string.Empty;
        }
        #endregion

        #region UI更新
        public delegate void UpdateString(object NewData);
        public void UpdateRecevie(object NewData)
        {
            if (this.InvokeRequired)//等待异步
            {
                UpdateString _myInvoke = new UpdateString(UpdateRecevie);
                this.Invoke(_myInvoke, new object[] { NewData });
            }
            else
            {
                txtReceive.AppendText(NewData.ToString());
                txtReceive.SelectionStart = txtReceive.Text.Length - 1;
                txtReceive.ScrollToCaret();
                serialdata = txtReceive.Text;

            }
        }
        public void UpdateReceiveCount(object NewCount)
        {
            if (this.InvokeRequired)//等待异步
            {
                UpdateString _myInvoke = new UpdateString(UpdateReceiveCount);
                this.Invoke(_myInvoke, new object[] { NewCount });
            }
            else
            {
                lblRCount.Text = (Convert.ToInt32(lblRCount.Text) + Convert.ToInt32(NewCount)).ToString();
            }
        }
        #endregion

        #region 其他
        private void TMenu_Byte_Click(object sender, EventArgs e)
        {
            //BCWin.Show();
        }

        private void TMenu_C_Click(object sender, EventArgs e)
        {
            Cwin.Show();
        }
        private void TMenu_AboutMe_Click(object sender, EventArgs e)
        {
            new SubWin.AboutMe().ShowDialog();
        }
        private void btnClearCount_Click(object sender, EventArgs e)
        {
            lblRCount.Text = "0";
            lblSCount.Text = "0";
        }
        #endregion



        //延时函数
        public static void Delay(int milliSecond)
        {
            int start = Environment.TickCount;
            while (Math.Abs(Environment.TickCount - start) < milliSecond)
            {
                Application.DoEvents();
            }
        }

    }
}


回复

使用道具 举报

0

精华

10

贡献

127

赞扬

帖子
21
软币
262
在线时间
20 小时
注册时间
2021-6-7
 楼主| 发表于 2021-7-15 17:48:47 | 显示全部楼层
高手来解答一下!
回复

使用道具 举报

Archiver|手机版|小黑屋|开发者网 ( 苏ICP备08004430号-2 )
版权所有:南京韵文教育信息咨询有限公司

GMT+8, 2024-4-24 05:37

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表