【发布时间】:2012-11-20 21:39:25
【问题描述】:
解决方案
通过“port.ReadByte”逐字节读取数据太慢,问题出在 SerialPort 类内部。 我将其更改为通过“port.Read”读取更大的块,现在没有缓冲区溢出。
虽然我自己找到了解决方案,但写下来对我有帮助,也许其他人也有同样的问题,并通过谷歌找到了这个......
(如何将其标记为已回答?)
编辑 2
通过设置
port.ReadBufferSize = 2000000;
我可以将问题延迟约 30 秒。所以看起来,.Net真的太慢了...... 由于我的应用程序不是那么重要,我只是将缓冲区设置为 20MB,但我仍然对原因感兴趣。
编辑
我刚刚测试了一些我以前没有想到的东西(我感到羞耻):
port.ErrorReceived += (object self, SerialErrorReceivedEventArgs se_arg) => { Console.Write("| Error: {0} | ", System.Enum.GetName(se_arg.EventType.GetType(), se_arg.EventType)); };
看来我已经超支了。 .Net 实现对于 500k 来说太慢了还是我这边有错误?
原始问题
我构建了一个非常原始的示波器(avr,它通过 uart 将 adc 数据发送到 ftdi 芯片)。在 pc 端,我有一个 WPF 程序来显示这些数据。
Protokoll 是:
两个同步字节 (0xaffe) - 14 个数据字节 - 两个同步字节 - 14 个数据字节 - ...
我使用 16 位值,因此 14 个数据字节内有 7 个通道(lsb 优先)。
我用 hTerm 验证了 uC 固件,它确实发送和接收一切正确。 但是,如果我尝试用 C# 读取数据,有时会丢失一些字节。 oszilloscop 程序一团糟,但我创建了一个小示例应用程序,它具有相同的症状。
我添加了两个扩展方法 a) 从 COM 端口读取一个字节并忽略 -1 (EOF) b) 等待同步模式。
示例程序首先通过等待 (0xaffe) 同步到数据流,然后将接收到的字节与预期值进行比较。循环运行几次,直到弹出断言失败消息。 我无法通过谷歌找到任何有关丢失字节的信息,我们将不胜感激。
代码
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SerialTest
{
public static class SerialPortExtensions
{
public static byte ReadByteSerial(this SerialPort port)
{
int i = 0;
do
{
i = port.ReadByte();
} while (i < 0 || i > 0xff);
return (byte)i;
}
public static void WaitForPattern_Ushort(this SerialPort port, ushort pattern)
{
byte hi = 0;
byte lo = 0;
do
{
lo = hi;
hi = port.ReadByteSerial();
} while (!(hi == (pattern >> 8) && lo == (pattern & 0x00ff)));
}
}
class Program
{
static void Main(string[] args)
{
//500000 8n1
SerialPort port = new SerialPort("COM3", 500000, Parity.None, 8, StopBits.One);
port.Open();
port.DiscardInBuffer();
port.DiscardOutBuffer();
//Sync
port.WaitForPattern_Ushort(0xaffe);
byte hi = 0;
byte lo = 0;
int val;
int n = 0;
// Start Loop, the stream is already synced
while (true)
{
//Read 7 16-bit values (=14 Bytes)
for (int i = 0; i < 7; i++)
{
lo = port.ReadByteSerial();
hi = port.ReadByteSerial();
val = ((hi << 8) | lo);
Debug.Assert(val != 0xaffe);
}
//Read two sync bytes
lo = port.ReadByteSerial();
hi = port.ReadByteSerial();
val = ((hi << 8) | lo);
Debug.Assert(val == 0xaffe);
n++;
}
}
}
}
【问题讨论】:
-
检查,检查,再检查双方在串行参数上是否完全一致(您指出的是 500000 8n1)。
-
具有相同参数的 hterm 接收所有内容(检查超过 20 秒),而我的控制台程序每约 1 秒丢失几个字节。我稍微修改了示例源代码,并添加了两张图片。我不能在这里发布它们,所以这是一个链接:skydrive.live.com/…
-
我刚刚测试了一些我早该想到的东西:我添加了
port.ErrorReceived += (object self, SerialErrorReceivedEventArgs se_arg) => { Console.Write("| Error: {0} | ", System.Enum.GetName(se_arg.EventType.GetType(), se_arg.EventType)); };行,看来问题是超限。现在我的问题是,我可以解决这个问题吗?如果可以,如何解决?如果我自己发现了什么,我会在这里报告。
标签: .net serial-port overrun