[英]is this a valid array for arduino and C++
我想使用以下命名約定創建多個數組
const int zone2[] = {11};
const int zone3[] = {12,13};
const int zone4[] = {14};
然后我想創建一個循環並檢查獲取數組的值,我正在做以下事情。
// read the state of the pushbutton value:
byte myInput =2;
//Outer loop checks the state of the Input Pins
//Inner loop iterates through corresponding array and pulls pins high or low depending on ButtonState
for (myInput = 2;myInput<5; myInput++) {
buttonState = digitalRead(myInput);
int ArrayCount;
String zoneChk = "zone" + String(myInput);
ArrayCount = sizeof(zoneChk) / sizeof( int ) ; // sizeof( int ) is the newpart
int arrayPosition;
for (arrayPosition = 0;arrayPosition < ArrayCount ; arrayPosition++) {
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(zoneChk[arrayPosition], HIGH);
}
else {
// turn LED off:
digitalWrite(zoneChk[arrayPosition], LOW);
}
}
}
有人告訴我該數組對C ++ arduino無效,我不太確定,只是隨便學習。 我希望控制一些房屋照明燈,這些區域是有效的房間,而數組的內容是房間內的不同燈光。 我將它們稱為Zones'x',因此我可以減少檢查每個房間的開關所需的代碼。
謝謝
String zoneChk = "zone" + String(myInput); ArrayCount = sizeof(zoneChk) / sizeof( int ) ; // sizeof( int ) is the newpart
不,不,不,不。
const int * const zones[] = {zone2, zone3, zone4};
...
for (int z = 0; z < 3; ++z)
{
// access zones[z]
}
另外,請考慮對每個zoneX
(以及可選的zones
)進行空終止,以便您知道何時到達末尾。
String zoneChk = "zone" + String(myInput);
ArrayCount = sizeof(zoneChk) / sizeof( int ) ; // sizeof( int ) is the newpart
這將不允許您在運行時訪問zone2..5變量。 您正在創建一個與zone2變量無關的“ zone2”字符串。
下面的代碼可以編譯,但是我沒有Arduino可以對其進行全面測試。 它仍然允許您更改zone2、3、4的大小,而無需對代碼進行任何修改。 如果您需要更多區域,則必須添加更多的case語句(包括注釋掉的zone5代碼)。
如果您希望它是完全動態的,我們可以為區域使用多維數組,但這應該是最少代碼的一個很好的開始
for (myInput = 2;myInput<5; myInput++) {
int buttonState = digitalRead(myInput);
int ArrayCount;
const int *zoneChk;
//This is the part you will have to add to if you want more zones
switch(myInput){
case 2:
ArrayCount = sizeof(zone2) / sizeof (zone2[0]);
zoneChk = zone2;
break;
case 3:
ArrayCount = sizeof(zone3) / sizeof (zone3[0]);
zoneChk = zone3;
break;
case 4:
ArrayCount = sizeof(zone4) / sizeof (zone4[0]);
zoneChk = zone4;
break;
//ex. case 5
//case 5:
// ArrayCount = sizeof(zone5) / sizeof (zone5[0]);
// zoneChk = zone5;
//break;
}
int arrayPosition;
for (arrayPosition = 0;arrayPosition < ArrayCount ; arrayPosition++) {
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(zoneChk[arrayPosition], HIGH);
}
else {
// turn LED off:
digitalWrite(zoneChk[arrayPosition], LOW);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.