Arduino-如何从serial.read()提供结构? [英] Arduino - how to feed a struct from a serial.read()?

查看:272
本文介绍了Arduino-如何从serial.read()提供结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个初学者,我正在尝试用一个具有指针的BIN类型的4个成员来提供一个结构表,然后将它们发送给另一个成员,serial2.我没有这样做.

I am a beginner and I am trying to feed a struct table with 4 members typed BIN with a pointer, then send them to another one, serial2. I fail to do so.

我从serial1.read()收到4个字符,例如'A''10''5''3'. 为了减少数据的大小,我想使用一个结构:

I receive 4 chars from serial1.read(), for example 'A' '10' '5' '3'. To decrease the size of the data, I want to use a struct:

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)
};

我声明并设置:实例和指针

I declare and set: instance and pointer

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();

以此类推.但这不起作用...

And so on. But it's not working...

我尝试提供第一个char表并尝试强制转换结果:

I tried to feed a first char table and tried to cast the result:

(*PtrProgs).page = PtrT[1], BIN;

现在,我意识到我一次不能喂3个位! h!所有这一切似乎都很薄弱,对于仅4个值来说肯定是一个过长的过程. (我想保留这种结构表以用于更多实例).

And now, I realize I can not feed 3 bits in one time! doh! All this seems very weak, and certainly a too long process for just 4 values. (I wanted to keep this kind of struct table for more instances).

请,您能帮我找到一种更简单的方法来喂养我的桌子吗?

Please, could you help me to find a simpler way to feed my table?

推荐答案

您只能通过串行端口发送完整的字节.但是您也可以直接发送原始数据.

You can only send full bytes over the serial port. But you can also send raw data directly.

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));
}

您还必须注意,在所有CPU上,sizeof(int)都不相同

You also have to be aware that sizeof(int) is not the same on all CPUS

关于字节序的词.如果在具有不同字节序的CPU上运行,则串行链接另一端的程序结构定义将变为:

A word about endianness. The definition for your struct for the program at the other end of the serial link, if running on a CPU with a different endianness would become:

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位.

Note the use of short int, which you can also use in the arduino code to be more precise. The reason is that short int is 16 bits on most CPUs, while int may be 16,32 or even 64 bits.

这篇关于Arduino-如何从serial.read()提供结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆