簡體   English   中英

將字節作為字節從arduino發送到C#程序失敗

[英]Sending Ints as bytes from arduino to C# program fails

我正在使用VS2010 C#中的程序。 它具有GUI,可用於通過串行端口與Arduino交互。

我遇到的問題是從arduino發送一個大於128(???)的字節值到程序。 我在arduino上獲得了一個整數值,將其分為highBite和lowByte,然后將每個值發送,然后在另一端進行重組。 如果我發送600,它將發送2的highByte和88的lowByte,並且通過對highByte的<<< 8進行位重組,它正確地重組為600。

如果我嘗試發送應為188和2的700,那么我在C#中看到188顯示為63。為什么? 在arduino和C#上均應為無符號字節,因此我不確定發生了什么問題。

Arduino代碼(相關部分):(0x43向C#發出信號,指示它正在接收哪個數據包)

byte bytesToSend[3] = {0x43, byte(88), byte(2)}; // 600 broken down to high and low bytes
Serial.write(bytesToSend, 3); // send three bytes
Serial.println(); //send line break to terminate transmission

byte bytesToSend[3] = {0x43, byte(188), byte(2)}; // 700 broken down to high and low bytes
Serial.write(bytesToSend, 3); // send three bytes
Serial.println(); //send line break to terminate transmission

C#代碼:(相關部分-自從我剪切/修剪和粘貼以來,可能錯過了一兩個語法)

string inString = "";
inString = port.ReadLine(); // read a line of data from the serial port
inString = inString.Trim(); //remove newline

byte[] buf = new byte[15]; // reserve space for incoming data
buf = System.Text.Encoding.ASCII.GetBytes(inString); //convert string to byte array I've tried a block copy here, but it didn't work either...

Console.Write("Data received: H: {0}, L: {1}. =", buf[2], buf[1]); //display high and low bytes
Console.WriteLine(Convert.ToUInt32((buf[2] << 8) + buf[1])); //display combined value

這就是我在串行監視器中得到的,它在其中寫出值:

Data received: H: 2, L: 88. = 600
Data received: H: 2, L: 63. = 575

在此過程中的某個位置,低字節值從188更改或誤解為63。 是什么原因造成的,我該如何解決? 當字節值小於128時似乎工作正常,但當字節值大於128時工作不正常。

我認為這可能是您的C#側代碼的問題。 您應該通過在port.ReadLine()之后打印要讀取的字符串來調試它,以查看所接收的內容。

我也建議使用C#Read(Byte [],Int32,Int32),以便將您的數據讀入字節數組,即無符號字符數組。 ReadLine()正在將數據讀入字符串(char數組)。

您的編碼錯誤。 將行從:

buf = System.Text.Encoding.ASCII.GetBytes(inString);

buf = System.Text.Encoding.GetEncoding("Windows-1252").GetBytes(inString);

更好的是,當實例化Port對象時,只需將編碼器屬性設置為此類型。

...
SerialPort port = new SerialPort();
System.Text.Encoding encoder = System.Text.Encoding.GetEncoding("Windows-1252");
port.Encoding = encoder;
...

請記住,ASCII是7位,因此您將截斷大於十進制127的值。1252編碼是8位,非常適合二進制數據。 MSDN上顯示的表顯示了對編碼的完整符號支持。

為什么在C#中讀取完整的字符串-這將迫使您處理編碼...-並進行后處理而不是及時解析?

System.IO.BinaryReader bin_port=new System.IO.BinaryReader(port); //Use binary reader
int b;
int data16;
b=bin_port.ReadByte();
switch (b) {
case 0x43: //Read integer
    data16=bin_port.ReadUInt16();
    while (bin_port.ReadByte()!=0x0a); //Discard all bytes until LF
    break;
}

暫無
暫無

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

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