【问题标题】:C# Can't read full buffer from serial port ArduinoC# 无法从串口 Arduino 读取完整缓冲区
【发布时间】:2014-05-11 05:03:35
【问题描述】:

我已将 Arduino 连接到串行端口。 Arduino 有以下简单的代码来发送字节:

void setup()
{
    Serial.begin(9600);
}

void loop()
{
    Serial.write((char)100);
}

接收字节的代码(在单独的线程中):

int buffersize = 100000;
byte[] buffer = new byte[buffersize];

SerialPort port = new SerialPort("COM3", 9600);
port.ReadBufferSize = buffersize;
port.Open();

int bytesread = 0;
do
{
    bytesread = port.BytesToRead;
}
while(bytesread < buffersize && bytesread != buffersize);

port.Read(buffer, 0, buffersize);

我读到 BytesToRead 可以返回比 ReadBufferSize 更多的内容,因为它包含一个缓冲区。但相反,我只能收到近 12000 个,之后 ReadBufferSize 不会改变。所有波特率都会出现同样的问题。

那么如何一次读取缓冲区中的所有 100000 个字节?也许有一些驱动程序设置等? 请帮忙。

【问题讨论】:

  • 您应该读取缓冲区中可用的任何内容并将其粘贴到其他地方进行处理。再读一遍,依此类推。

标签: c# serial-port arduino


【解决方案1】:

如果 Arduino 以该波特率连续发送字节,则最大速度为 9600/10 = 960 字节/秒(1 个字节需要 10 个波特:8 个数据位 + 1 个开始 + 1 个停止)。然后将在 104 秒以上收集 100000 个字节。如果通信没有中断,您的代码应该可以工作。要调试它,你可以在你的 while 循环中添加它:

System.Threading.Thread.Sleep(1000); //sleep 1 second
Console.WriteLine("Total accumulated = " + bytesread);

不过,更好的方法是使用SerialPortDataReceived 事件:

int buffersize = 100000;
SerialPort port = new SerialPort("COM3", 9600);

port.DataReceived += port_DataReceived;

// To be safe, set the buffer size as double the size you want to read once
// This is for the case when the system is busy and delays the event processing
port.ReadBufferSize = 2 * buffersize;

// DataReceived event will be fired when in the receive buffer
// are at least ReceivedBytesThreshold bytes
port.ReceivedBytesThreshold = buffersize; 
port.Open();

事件处理程序:

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    // The event will also be fired for EofChar (byte 0x1A), ignore it
    if (e.EventType == SerialData.Eof)
        return;

    // Read the BytesToRead value, 
    // don't assume it's exactly ReceivedBytesThreshold
    byte[] buffer = new byte[port.BytesToRead];
    port.Read(buffer, 0, buffer.Length);

    // ... Process the buffer ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-13
    • 1970-01-01
    • 2012-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多