c++ - Arduino Uno - serial.read 到位结构

标签 c++ c arduino

这个问题是在这篇文章之后提出的:arduino - how to feed a struct from a serial.read()

首先,我要感谢 Sol Arnu 之前提供的代码,如下所示。请注意该代码是高效的。迄今为止最好的尝试。即使我认为没有任何内容被发送到桌面上。现在我可以打印“1”了。但是,如果我更改发送的页面(2 而不是 1),则不会发生任何变化。这部分 x.b = val1 | (val2<<8); Serial.print(x.a.page); 让我感到困惑。它是否比较 2 个 var 位并通过 union 将结果放入结构体实例中?

我并没有说它是 Arduino Uno(8 位、内存和寄存器)。你能看到发生了什么吗?

#include <SoftwareSerial.h>
#define PACKED __attribute__((__packed__))

SoftwareSerial PORTone(8, 9); // port 1
SoftwareSerial PORTtwo(10, 11); // port 2

PACKED union {
  PACKED struct {
unsigned int val1:
    1; // (0,1)
unsigned int val2:
    4; // 10 choices (4 bits)
unsigned int val3:
    3; // 5 choices (3 bits)
unsigned int val4:
    2; // 3 choices (2 bits)
  }
  *PtrStr;
  uint8_t  val_table[2];
  uint16_t b;
}
*MegaUnion;

//*********************************SETUP***************
void setup() {
  Serial.begin(9600);
  PORTone.begin(9600);
}

//**********************************LOOP***************
void loop() {
  while(PORTone.available()>0) {
    delay(100);
    for(int i = 0; i<=4; i++) {    
      for(int i = 0; i<=3; i++) {  
        for( int j = 0; j<=3; j++) {
          int inByte = PORTone.read();         
          *MegaUnion.struct.val1[j] = inByte; // error: 'union<anonymous>' has no member named 'val1'
        }
        //  I should that too
        //  u_structTable x;
        //  x.b = val1 | (val2<<8);
        //  Serial.print(x.a.page); 
      }  
    } 
    // what is coming from the table
    Serial.print( (*MegaUnion).page);
  }
}

我应该回答 Michaël Roy(希望我可以通过第二个线程)。感谢您的宝贵回答。这似乎是我要测试的另一种方法。

“编辑”我还纠正了尼克·加蒙(Nick Gammon)很好地发现的一个大错误,以便更好地了解该主题。我的错。

最佳答案

也许这个 union 涵盖了所有类型,并且因为它使用匿名结构,所以需要的点更少:):

#define PACKED __attribute__((__packed__))

PACKED union {
    PACKED 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)
    };
    PACKED struct
    {
        uint8_t val1;
        uint8_t val2;
    };
    uint8_t  val_table[2];
    uint16_t b;
}MegaUnion;

MegaUnion.val1 = PORTone.read();
MegaUnion.val2 = PORTone.read();

请记住,您的页面位域占据 union 中最年轻的位,因此要将其设置为 one,您需要编写 MegaUnion.val1 = 1MegaUnion。 val_table[0] = 1MegaUnion.b = 1

关于c++ - Arduino Uno - serial.read 到位结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45623729/

相关文章:

C - 使用 lseek 向后移动文件中的指针

c - Modbus 主从通信

c++ - 指针数组和指向指针数组的指针

arduino - 为什么 Arduino 程序称为草图?

python - 使用 pySerial 从 Python 获取输入/输出错误

python - 在 Boost Python 中公开模板化基类的最佳方式?

c++ - 如何使用 VTK 原始保存 DICOM 系列

c++ - 测量 OpenCL 应用程序的运行时间

c - 错误: How to fix the digitalWrite() error?

c++ - 类析构函数错误