繁体   English   中英

如何用自定义类型声明Arduino数组?

[英]How to declare Arduino array with custom type?

我将Arduino项目OneWire库Dallas用于我的Arduino项目。 这定义了一个DeviceAddress类型,可以包含一个OneWire设备地址。 我想创建一个数组来存储我的设备地址,因此可以在它们上循环。

以下未编译

DeviceAddress waterTempSensorAddress = { 0x28, 0xCA, 0x98, 0xCF, 0x05, 0x0, 0x0, 0x51 };
DeviceAddress heatWaterSystemTemSensorAddress   = { 0x28, 0xC4, 0xA8, 0xCF, 0x05, 0x0, 0x0, 0xC6 };

DeviceAddress test[] = { waterTempSensorAddress, heatWaterSystemTemSensorAddress };

错误是:

pool_manager:62: error: array must be initialized with a brace-enclosed initializer DeviceAddress test[] = { waterTempSensorAddress, heatWaterSystemTemSensorAddress }; ^

可以为此声明一个类似Arduino的数组吗? 我应该考虑使用其他结构吗?

谢谢,

它不是真正的自定义类型,只是typedef uint8_t DeviceAddress[8]; 和数组不能像类一样进行复制构造。

基本上,您有两种简单的方法可以做到这一点:

// #1
DeviceAddress test[] = { { 0x28, 0xCA, 0x98, 0xCF, 0x05, 0x0, 0x0, 0x51 }, { 0x28, 0xC4, 0xA8, 0xCF, 0x05, 0x0, 0x0, 0xC6 } };
// and eventually you can define:
DeviceAddress  *waterTempSensorAddress = test;
DeviceAddress  *heatWaterSystemTemSensorAddress = test + 1; 

但这不是很好。

另一种方法是使用指针:

// #2
DeviceAddress waterTempSensorAddress = { 0x28, 0xCA, 0x98, 0xCF, 0x05, 0x0, 0x0, 0x51 };
DeviceAddress heatWaterSystemTemSensorAddress   = { 0x28, 0xC4, 0xA8, 0xCF, 0x05, 0x0, 0x0, 0xC6 };
DeviceAddress * test2[] = { &waterTempSensorAddress, &heatWaterSystemTemSensorAddress };

第一个更易于使用,第二个更不易读:

void da(DeviceAddress const& addr) { /*  ....  */ }

void something() {
  da(test[0]);  // #1

  da(*(test2[0])); // #2 
  da(test2[0][0]); // #2 (it's basically two dimensional array of DeviceAddress)
}

无论如何,这都是关于C ++基础知识的。

有点困难的方法是使用容器类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM