zoukankan      html  css  js  c++  java
  • 串口高波特率丢失字符

    void DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            if (!serialPort.IsOpen)
            {
                return;
            }        
    
            Byte[] receivedData = new Byte[serialPort.BytesToRead];        //创建接收字节数组
            serialPort.Read(receivedData, 0, receivedData.Length);         //读取数据
    
            serialPort.DiscardInBuffer();
            serialPort.DiscardOutBuffer();
    
            string read = Encoding.ASCII.GetString(receivedData);
    
            read = read.Replace("", "");        
        }
        catch (Exception ex)
        {        
        }  
    }

    在DataReceived方法里,使用上面的方式,在大波特率,比如115200会出现read丢字符的现象。使用下面的方式,没有出现。

    void DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            if (!serialPort.IsOpen)
            {
                return;
            }
    int n = serialPort.BytesToRead; byte[] buf = new byte[n]; int readLength = 0; int offset = 0; while (offset < n) { readLength = serialPort.Read(buf, 0, n - offset); if (readLength < 0) { return; } offset = offset + readLength; }
        
    string read = Encoding.ASCII.GetString(buf); } catch (Exception ex) { } }
  • 相关阅读:
    java基础 类 & 继承
    java基础之 hashmap
    tomcat 详解
    hash算法
    素数
    『战略游戏 最大利润 树形DP』
    『宝藏 状态压缩DP NOIP2017』
    『玩具装箱TOY 斜率优化DP』
    『数组的最大代价 贪心优化DP』
    『最大M子段和 线性DP』
  • 原文地址:https://www.cnblogs.com/code1992/p/13261832.html
Copyright © 2011-2022 走看看