[英]Why is my serial.write sending data twice
我正在嘗試通過創建一個應用程序來模擬微控制器通過串行端口發送數據,該應用程序使用接收例程將字節連續發送到另一個應用程序以用於 GUI 目的。
我正在使用此方法從發件人實例發送我的字節:
Write(vout, 0, 13);
Write 定義為:
public void Write(byte[] buffer, int offset, int count)
{
// preconditions checks are omitted
serialPort1.Write(buffer, offset, count);
}
vout是我從實時模擬傳感器的數據中手動填充的字節數組。
在 GUI 應用程序中接收數據時,我使用的是:
private void comport_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (!comport.IsOpen) return;
int bytes = comport.BytesToRead;
//For loop for getting all values in buffer to 0
comport.Read(buffer, 0, 13);
Update_counter();//Updates counter by 1.
}
第二次/之后的任何時候我發送了一些東西,它被發送了兩次,或者至少這是我的計數器變量所暗示的。
我不確定這是否與實際的串行緩沖區有關,或者我是否錯誤地使用了寫入和讀取方法。
此外,我將 COMPORT 設置為 9600 波特率、8 位、停止位 1、無奇偶校驗。
任何幫助表示贊賞。
問題的原因是,您正在讀取比現在可用的字節更多的字節:
int nrOfAvailableBytes = comport.BytesToRead;
comport.Read(buffer, 0, 13);
所以即使comport告訴你只有一個字節可用,你還是決定讀取13個字節。
SerialPort.Read告訴你:
如果計數大於輸入緩沖區中的字節數,則讀取的字節較少。
解決方案:只讀取當前可用的字節。
不要忽略Read()
返回的值,它返回放入緩沖區的字節數。 因此,如果您想讀取 13 個字節,但返回的字節數少於此,請跟蹤計數並讀取,直到達到所需的字節數。
換句話說,你將不得不實現你的//For loop
注釋:
int totalBytesRead = 0;
int bytesToRead = 13;
do
{
totalBytesRead += comport.Read(buffer, 0, bytesToRead - totalBytesRead);
}
while (totalBytesRead < bytesToRead);
通過結合這兩個答案,我能夠得到一致的結果。 我覺得有點多余,但這是最有希望的。
int n_available_bytes = comport.BytesToRead;
//Reset buffer array
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = 0;
}
//Read, update charts, save to CSV only when the buffer has all the bytes
if (n_available_bytes == bytesToRead)
{
do
{
totalBytesRead += comport.Read(buffer, 0, bytesToRead - totalBytesRead);
}
while (totalBytesRead < bytesToRead);
if (totalBytesRead == bytesToRead)
{
totalBytesRead = 0;
}
HandleSerialData(buffer);
this.Invoke(new EventHandler(Fill_chart));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.