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

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

问题描述

我是一个初学者,我试图用一个指针输入一个有 4 个成员的结构表,输入 BIN,然后将它们发送到另一个,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;

然后我尝试像这样喂食:

Then I try to feed like this:

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

我尝试提供第一个字符表并尝试转换结果:

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

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

现在,我意识到我不能一次喂 3 位!哦!所有这些看起来都很弱,而且对于仅 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));
}

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

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代码中使用它来更精确.原因是short int 在大多数CPU 上都是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天全站免登陆