使用UART发送结构 [英] Send a structure using UART
问题描述
我有两个委员会:
-主板(M板)
-从板(S板)
I have a two boards:
- Master board (M board)
- Slave board (S board)
M董事会应向S董事会发送请求,后者应予以答复.
M board shall send a request to S board and the latter shall answer.
奴隶的答案是一个结构:
The answer of the slave is a struct:
typedef struct{
uint8_t userID;
uint8_t userPass;
uint16_t userData;
}UserTypeDef;
UserTypeDef User;
示例:
M板通过发送命令GET_USER_INFO询问用户信息(结构). S板应将数据结构返回给M板.
Example:
M board asks for user's information (struct) by sending the command GET_USER_INFO. S board shall return a data structure to M board.
M板(Tx)-> GET_USER_INFO->(Rx)S板
S板(Tx)->用户->(Rx)M板
M Board(Tx) --> GET_USER_INFO --> (Rx)S Board
S Board(Tx) --> User --> (Rx)M Board
问题是如何使用UART发送这样的结构?
The question is how to send such a struct using UART ?
推荐答案
编写一个协议文档,该协议文档明确定义了如何通过网络媒体传输结构的内容.然后编写代码以实现该协议.
Write a protocol document that explicitly defines how the contents of the structure should be transmitted over the network media. Then write code to implement the protocol.
传输结构/对象的代码是"序列化数据.接收结构/对象的代码是反序列化".您可以向Google获取有关各种序列化协议和技术的大量建议和示例.
The code that transmits the structure/object is "serializing" the data. The code that receives the structure/object is "deserializing". You can Google for lots of advice and examples about a variety of serialization protocols and techniques.
如果您使用的是二进制协议,则可以通过定义uint8_t指针以指向结构中的第一个字节来序列化C结构,然后传输这些字节,直到传输完整个sizeof(struct)
. 但是这种方法有一些陷阱,尤其是在您的发送和接收设备使用不同的微控制器和/或C编译器的情况下.如果一个微控制器使用的字节序不同于另一个微控制器,或者一个C编译器使用的结构填充规则不同于另一个微控制器,则反序列化的数据可能会被破坏.
If you're using a binary protocol then you could serialize a C struct, by defining a uint8_t pointer to point to the the first byte in the structure and then transmit the bytes until you've transmitted the entire sizeof(struct)
. But this method has some pitfalls, especially if your transmitting and receiving devices use different microcontrollers and/or C compilers. If one microcontroller uses a different endianness than the other, or if one C compiler uses different struct padding rules than the other, then the deserialized data could be corrupted.
这就是为什么您必须编写一个协议文档来明确定义每个字节的顺序和含义的原因.而且,您不应该依赖C编译器来组织与协议完全相同的结构. C编译器可能会插入填充或可能使用了错误的字节序.因此,您不应该编写简单的序列化和反序列化例程,而是从网络协议消息中解析出每个字节,然后将其复制到结构中的适当字节,或从中复制相应的字节,而不是简单地通过该结构增加指针.
This is why you have to write a protocol document that explicitly defines the order and meaning of each byte. And you shouldn't rely on your C compiler to organize the struct exactly like your protocol. The C compiler may insert padding or may use the wrong endianness. So instead of simply incrementing a pointer through the struct, you should write serialization and deserialization routines that parse out each byte from the network protocol message and copy it to/from the appropriate byte in the struct.
这篇关于使用UART发送结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!