我是一名初学者,我正在尝试向一个结构表提供 4 个用指针键入 BIN 的成员,然后将它们发送到另一个结构表,serial2。我没能做到。
我从 serial1.read()
收到 4 个字符,例如 'A' '10' '5' '3'。
为了减少数据的大小,我想使用结构:
struct structTable {
unsigned int page:1; // (0,1)
unsigned int cric:4; // 10 choices (4 bits)
unsigned int crac:3; // 5 choices (3 bits)
unsigned int croc:2; // 3 choices (2 bits)
};
我声明并设置:实例和指针
struct structTable structTable;
struct structTable *PtrstructTable;
PtrstructTable = &structTable;
然后我尝试这样喂食:
for(int i = 0; i<=4; i++) {
if(i == 1) {
(*PtrProgs).page = Serial.read();
if(i == 2) {
(*PtrProgs).cric = Serial.read();
等等。但它不起作用...
我尝试输入第一个字符表并尝试转换结果:
(*PtrProgs).page = PtrT[1], BIN;
现在,我意识到我无法一次喂 3 位!哦!所有这些看起来都很弱,而且对于只有 4 个值的情况来说,当然是一个太长的过程。 (我想为更多实例保留这种结构表)。
请问您能帮我找到一种更简单的方法来满足我的餐 table 需求吗?
最佳答案
您只能通过串行端口发送完整字节。但您也可以直接发送原始数据。
void send (const structTable* table)
{
Serial.write((const char*)table, sizeof(structTable)); // 2 bytes.
}
bool receive(structTable* table)
{
return (Serial.readBytes((char*)table, sizeof(structTable)) == sizeof(structTable));
}
您还必须注意 sizeof(int) 在所有 CPU 上都不相同
关于字节顺序的一句话。如果在具有不同字节序的 CPU 上运行,则串行链路另一端的程序的结构定义将变为:
struct structTable {
unsigned short int croc:2; // 3 choices (2 bits)
unsigned short int crac:3; // 5 choices (3 bits)
unsigned short int cric:4; // 10 choices (4 bits)
unsigned short int page:1; // (0,1)
};
注意短整型的使用,您也可以在arduino代码中使用它以更精确。原因是short int在大多数CPU上是16位,而int可能是16,32甚至64位。
关于c++ - Arduino - 如何从serial.read()提供结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45600202/