吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1707|回复: 8
收起左侧

[求助] C#串口通信读入的数据显示不正常,求大佬帮忙看看哪儿出现问题了

[复制链接]
老狗丶 发表于 2020-5-24 07:22
C#串口通信读入的数据显示不正常,求大佬帮忙看看哪儿出现问题了

VS2015项目源程序连接:https://lanzouj.com/icxz9od,
.cs代码段如下
[C#] 纯文本查看 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
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 dotNet实现与扫码枪USB通讯
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
            this.Load += FrmMain_Load;
        }

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

        NewLandSerial newland;

        private string portNo;

        private void tsb_Connect_Click(object sender, EventArgs e)
        {
            newland = new NewLandSerial();
            //4、绑定方法
            newland.myShowMsg += ShowMsg;
            portNo = ConfigurationManager.AppSettings["Port"].ToString();
            if (newland.OpenMyComm(9600, portNo, 8, Parity.None, StopBits.One))
            {
                MessageBox.Show("连接成功", "建立连接");
                this.tsb_Connect.Enabled = false;
                this.tsb_DisConnect.Enabled = true;
            }
            else
            {
                MessageBox.Show("连接失败", "建立连接");
            }
        }

        private void tsb_ParaSet_Click(object sender, EventArgs e)
        {
            new FrmSet().ShowDialog();
        }

        private void tsb_DisConnect_Click(object sender, EventArgs e)
        {
            if (newland.CloseMyComm())
            {
                MessageBox.Show("断开连接成功", "断开连接");
                this.tsb_Connect.Enabled = true;
                this.tsb_DisConnect.Enabled = false;
            }
            else
            {
                MessageBox.Show("断开连接失败", "断开连接");
            }
        }


        //3、根据委托类型创建方法
        private void ShowMsg(string Msg)
        {
            Invoke(new Action(() =>
                {
                    this.txt_Info.AppendText(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "    " + Msg + Environment.NewLine);
                }));
        }
    }
}






using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace dotNet实现与扫码枪USB通讯
{
    //1、创建委托
    public delegate void ShowMsgDelegate(string Msg);
    public class NewLandSerial
    {
        //创建串口对象
        private SerialPort MyComm;

        //2、创建委托对象
        public ShowMsgDelegate myShowMsg;
        public NewLandSerial()
        {
            MyComm = new SerialPort();
        }

        //打开串口方法
        public bool OpenMyComm(int iBaudRate,string PortNo,int DataBits,Parity iParity,StopBits istopbit)
        {
            try
            {
                if (MyComm.IsOpen)
                {
                    MyComm.Close();
                }
                MyComm.BaudRate = iBaudRate;
                MyComm.PortName = PortNo;
                MyComm.DataBits = DataBits;
                MyComm.Parity = iParity;
                MyComm.StopBits = istopbit;

                MyComm.ReceivedBytesThreshold = 1;      //每次只读一个字节
                MyComm.DataReceived += MyComm_DataReceived;

                MyComm.Open();
                return true;
            }
            catch (System.Exception ex)
            {
                return false;
            }
        }

        byte mReceivedByte;
        byte[] bData = new byte[1024];
        int mReceivedByteCount = 0;
        private void MyComm_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //接收数据

            while (MyComm.BytesToRead>0)
            {
                mReceivedByte = (byte)MyComm.ReadByte();
                bData[mReceivedByteCount] = mReceivedByte;
                mReceivedByteCount += 1;
                //异常处理,一次性字节太多
                if (mReceivedByteCount >= 1024)
                {
                    mReceivedByteCount = 0;
                    //清除输入缓冲区
                    MyComm.DiscardInBuffer();
                    return;
                }
            }
            //正常处理
            if (mReceivedByteCount > 0)
            {
                byte[] b = GetByteArray(bData, 0, mReceivedByteCount);

                //5、调用委托
                myShowMsg(Encoding.ASCII.GetString(b));
            }
        }

        /// <summary>
        /// 自定义截取字节数组
        /// </summary>
        /// <param name="byteArr"></param>
        /// <param name="start"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        private byte[] GetByteArray(byte[] byteArr,int start,int length)
        {
            byte[] Res = new byte[length];
            if (byteArr != null && byteArr.Length >= length)
            {
                for (int i = 0;i<length;i++)
                {
                    Res[i] = byteArr[i + start];
                }
            }
            return Res;
        }

        public bool CloseMyComm()
        {
            if (MyComm.IsOpen)
            {
                MyComm.Close();
            }
            return true;
        }

    }
}







测试图.png

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

xingzhe1314 发表于 2020-5-24 08:18
我也不懂,只是看着应该是前面发送的数据没自动停止,一直发送数据,比如第5次发送的,前4次的也在重复发送
xouou 发表于 2020-5-24 08:55
要么串口缓存没清除 , 要么你的读取变量没清除
bsjasd 发表于 2020-5-24 09:05
岔路ko 发表于 2020-5-24 09:07
[C#] 纯文本查看 复制代码
            If m_csSerialPort.BytesToRead > 0 Then
                Threading.Thread.Sleep(100)                   '增加延迟防止数据减少
                strDat = m_csSerialPort.ReadExisting.ToString '读取缓冲区中的数据
                m_csSerialPort.DiscardInBuffer()
            End If


我是直接用的  SerialPort控件做的
岔路ko 发表于 2020-5-24 09:17
岔路ko 发表于 2020-5-24 09:07
[C#] 纯文本查看 复制代码
            If m_csSerialPort.BytesToRead > 0 Then
                Threadi ...[/quote]

[mw_shl_code=csharp,true]        private void MyComm_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            System.Threading.Thread.Sleep(100);
            string response = MyComm.ReadExisting();
            MyComm.DiscardInBuffer();
            myShowMsg(response);
        }


基于你的程序修改的,测试OK Snipaste_2020-05-24_09-17-19.png
ky_wei 发表于 2020-5-24 09:33
清缓存,复循
he58394835 发表于 2020-5-24 10:24
学习中......学习中......
 楼主| 老狗丶 发表于 2020-5-24 10:26
  139行的      int mReceivedByteCount = 0;应放入紧挨着的MyComm_DataReceived函数内
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-1-15 17:57

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

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