簡體   English   中英

C#通過串口將int數組發送到arduino

[英]c# send int array via serial port to arduino

我正在嘗試使用串行端口從C#向Arduino發送一個int數組。 在C#中,首先我有輸入字符串

input = "98;1;5;160;0;255;421;101";

然后,我將其轉換為一個int數組

int [] sendint = input.Split(';').Select(n => Convert.ToInt32(n)).ToArray(); 
//this array is what I need to send to Arduino

然后,我將其轉換為字節數組以通過串行端口發送

byte[] sendbytes = sendint.Select(x => (byte)x).ToArray();
// because Write() requires byte, not int

最后,我發送

serialport.Write(sendbytes,0,sendbytes.Length); 
// port is open, baudrate is OK, portname is OK

然后,它應該由我的Arduino接收

int recdata[10];
int bytes = 0;
if(Serial.available())
{     
  while(Serial.available())
  {
    recdata[bytes]=Serial.read();
    bytes++;
  }
  checkdata(); //function which checks the received data
}

所以recdata應該是一個int數組

recdata = {98,1,5,160,0,255,421,101};

但事實並非如此。 當我將其打印到另一個串行端口進行檢查時。

for(int i = 0; i < 10; i++) //called befory checkdata() function in code above
{
  Serial1.print(recdata[i] + "  ");
}

我得到3個輸出,而不是1個,好像串行端口先發送一個int,然后發送第二個,然后發送其余的。

98  0  0  0  0  0  0  0  0  0  1checkfail //1checkfail is from function checkdata()
1  0  0  0  0  0  0  0  0  0  1checkfail //and it's saying, that data
5  160  0  255  165  101  0  0  0  0  1checkfail//are wrong

98 1    5  160   0   255 421 101 0  0 1checkok //this is how it should like
                      //421 and 165 - i know, that i'm trying to save 421 in byte, which has a limit of 256, so this is another problem

有人對這個問題有建議嗎?

我們應該看看您的checkdata()函數做什么,但是我很確定您沒有檢查bytes變量。

發生的事情是...。您正在使用串行通信。 這意味着您不會一次獲取所有數據,而是一次獲取一個字節。 如果您從PC發送8個字節,但是在收到兩個字節后檢查Serial.available()函數,您將僅得到2個答案。 我認為如果您以這種方式修改代碼

// Move these OUTSIDE the loop function
int recdata[10];
int bytes = 0;

// This is in the loop function
if(Serial.available())
{     
  while(Serial.available())
  {
    recdata[bytes]=Serial.read();
    bytes++;
  }
  if (bytes >= 8)
  {
    checkdata(); //function which checks the received data
    bytes = 0;
  }
}

它會正常工作...

否則...編寫您的checkdata函數,我們將看到。

順便說一句...我會在閱讀部分放一張支票,就像

while(Serial.available())
{
  if (bytes < 10)
  {
    recdata[bytes]=Serial.read();
    bytes++;
  }
}

因此,如果您收到的是12個字節而不是10個字節,則可以避免內存損壞。

Arduino循環正在趕上串行流,因此循環進入了3次,而不是一次。

您可以使用Serial.readBytes()代替Serial.read()。 它將一直填充緩沖區直到超時。 使用Serial.setTimeout()選擇一個合理的超時時間,而不是默認的1000毫秒。

char recdata[10];
int bytes = 0;
if(Serial.available())
{     
  bytes = Serial.readBytes(recdata, MAX_LENGTH);
  checkdata(); //function which checks the received data
}

有關將int轉換為字節的問題,請查看此問題。

暫無
暫無

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

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