簡體   English   中英

C#無法從串口Arduino讀取完整緩沖區

[英]C# Can't read full buffer from serial port Arduino

我已將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字節? 也許有一些驅動程序設置等? 請幫忙。

如果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 ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM