Arduino – 如何从serial.read()提供结构?
我是一个初学者,我正在尝试用一个带有指针的4个成员键入BIN的结构表,然后将它们发送到另一个,serial2。 我没有这样做。
我从serial1.read()
收到4个字符,例如’ serial1.read()
‘。 为了减小数据的大小,我想使用一个结构:
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();
等等。 但它不起作用……
我试图提供第一个char表并尝试转换结果:
(*PtrProgs).page = PtrT[1], BIN;
而现在,我意识到我不能一次喂3位! 卫生署! 所有这些看起来都很弱,而且对于4个值来说肯定是一个太长的过程。 (我希望为更多实例保留这种结构表)。
拜托,您能帮我找一个更简单的方法来喂我的餐桌吗?
您只能通过串行端口发送完整字节。 但您也可以直接发送原始数据。
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)在所有CPUS上都不相同
关于字节序的一个词。 如果在具有不同字节顺序的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) };
注意使用short int,你也可以在arduino代码中使用更精确。 原因是大多数CPU上的short int是16位,而int可能是16,32甚至64位。
根据Arduino引用,我只查了一下Serial :: read ,代码逐字节地返回数据(一次8位)。 所以你可能只需要读取一个字节的数据(一次8位)并在事后解压缩。
实际上你可能想要使用一个union
(参见例如关于如何使用union
其他stackoverflow文章 ),这样你就可以充分利用两个世界。 具体来说,如果定义一个定义的union
与断开的位以及并集的第二部分为一个或两个字节,则可以将数据作为字节发送,然后在您感兴趣的位中对其进行解码。
UPDATE
以下是对更多细节的尝试。 关于工会有很多警告 – 它们不可移植,它们依赖于编译器等等。但这可能值得尝试。
typedef struct { 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) } structTable; typedef union { structTable a; uint16_t b; } u_structTable; serial.Read(val1); serial.Read(val2); u_structTable x; xb = val1 | (val2<<8); printf("page is %d\n", xapage);