简体   繁体   English

如何通过串行端口向STM32发送字节数组?

[英]How to send byte array over Serial Port to STM32?

so I am trying to send some bytes with hex values to setup my microcontroller on the other side of Serial Port. 因此,我尝试发送一些带有十六进制值的字节以在串行端口的另一侧设置我的微控制器。 The thing is I am not quite sure how to properly do it and in what format to send them. 问题是我不太确定如何正确执行此操作以及以哪种格式发送它们。 For example I need to send two bytes and their hex values are 57 and B0 . 例如,我需要发送两个字节,它们的十六进制值为57B0 When I try to send it as a char array and I read it back I always get the ASCII Hex values of those characters like 53 and then 55 for the value 57 . 当我尝试将其作为char数组发送并读回时,我总是得到那些字符的ASCII十六进制值,例如53 ,然后是55的值57 So I wanted to format the hex value as a byte and send both of them at the same time from byte array but I am not getting anything when reading the response. 所以我想将十六进制值格式化为一个字节,然后从字节数组中同时发送两个值,但是读取响应时什么也没得到。 After formatting it to byte, the MessageBox is showing it's decimal value and I don't know if it supposed to be like that. 将其格式化为字节后,MessageBox将显示其十进制值,我不知道它是否应该像这样。 I am providing my code below. 我在下面提供我的代码。

Info_Byte_Dec += Protocol_Set + Protocol_Unit + Protocol_Write + Protocol_Settings; //stores decimal value
Data_Byte_Dec = Mode * Protocol_Mode_Offset + ODR * Protocol_ODR_Offset + Scale; //stores decimal value

Info_Byte_Hex = Info_Byte_Dec.ToString("X"); //convert to hex value
Data_Byte_Hex = Data_Byte_Dec.ToString("X"); //convert to hex value
string Merged = $"{Info_Byte_Hex} {Data_Byte_Hex}";
MessageBox.Show("Merged1: " + Merged);
byte[] Mergedbytes = Merged.Split(' ').Select(s => Convert.ToByte(s, 16)).ToArray();
MessageBox.Show("Merged2: " + Mergedbytes[0] + Mergedbytes[1]);

port.Write(Mergedbytes, 0, 2);

I am not sure whether I should just send the decimal value 87 , or I should format it to 57 hex value, or even to 0x57 . 我不确定我应该只发送十进制值87还是将其格式化为十六进制值57甚至0x57

usually in the microcontroller world when you use hex, you mean actual bytes, the hex is just a convenient notation to write binary byte values in, it usually never means send the ascii hex values. 通常在微控制器世界中,当您使用十六进制时,您指的是实际字节,十六进制只是一种方便的表示法,用于在其中写入二进制字节值,它通常从不意味着发送ascii十六进制值。 Having said that, there are no rules, and sometimes people do actual ascii hex. 话虽如此,没有规则,有时人们会使用实际的ASCII十六进制。

In your case, if you are using 0x57 on the stm32, it likely means you are using a byte literal, and not a ascii representation. 在您的情况下,如果您在stm32上使用0x57 ,则可能意味着您使用的是字节文字,而不是ascii表示形式。 You would have to do extra work to turn a 0x57 into a string. 您将需要做一些额外的工作才能将0x57转换为字符串。

So that means in C# just send bytes, not the ascii hex like you are at the moment 因此,这意味着在C#中仅发送字节,而不是像现在那样发送ascii十六进制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM