在JavaScript中,我可能会遍历一组包含数据的对象,如下所示:
const components = [
{
id: 1,
pin: "A0",
name: "light"
},
{
id: 2,
pin: "A1",
name: "sound"
},
{
id: 1,
pin: "A0",
name: "heat"
},
]
for (const component of components) {
const value = analogRead(component.pin);
console.log(`${component.name}:value`)
}我经常需要在Arduino上使用这样的代码,但我不确定我该如何去做。
注意:我并不是在寻找将其准确地翻译成C++;我想知道在使用Arduino时实现这一目标的标准模式是什么。
发布于 2019-08-24 23:59:13
您可以使用C structure。为此,您需要首先声明一个结构来描述您的对象类型。
struct component
{
int id;
char pin[10];
char name[50];
};
component components[] = {
{
1,
"A0",
"light"},
{
2,
"A1",
"sound"},
{
1,
"A0",
"heat"}
};
int main ()
{
int len = sizeof(components)/sizeof(components[0]);
for (int i=0 ; i<len ; i++)
{
printf("{ id: %d , pin: \"%s\" , name: \"%s\" }\n",components[i].id, components[i].pin, components[i].name);
}
return 0;
} 输出:
{ id: 1 , pin: "A0" , name: "light" }
{ id: 2 , pin: "A1" , name: "sound" }
{ id: 1 , pin: "A0" , name: "heat" }发布于 2019-08-24 23:51:21
如果您使用的是最新的C++ (11或更高版本,我知道arduino支持它),并且您的数据存储在一个数组中,您可以简单地执行以下操作:
int values[5] = { 16, 2, 77, 40, 12071 }
for(auto const& value: values) {
// Do stuff
}https://stackoverflow.com/questions/57639210
复制相似问题