gpt4 book ai didi

c - Arduino 阵列问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:32:44 25 4
gpt4 key购买 nike

您好,我正在做一个项目,用 Arduino 点亮我家的灯。

我让它以基本形式工作,现在我想存储电灯开关的先前状态。我正在使用一个存储开关当前状态的数组,以便可以在下一个循环中进行比较。我有 7 个开关,我创建了它,因此如果需要,一个开关可以打开许多灯。

我需要存储之前的状态,因为下一部分是介绍web控制,这个的测试项目已经写好了

奇怪的是7/8 区工作完美。其他区域打开,但不关闭。当我打开另一个开关时,如果它的开关处于关闭位置,灯可能会熄灭。

如果我删除前一个状态的条件,检查所有开关都很好。

const int zone2[] = {8,13,0};
const int zone3[] = {11,0};
const int zone4[] = {7,0};
const int zone5[] = {9,0};
const int zone6[] = {12,0};
const int zone7[] = {6,0};
const int zone8[] = {14,0};

const int * zones[]={zone2,zone3,zone4,zone5,zone6,zone7,zone8};

int buttonState[] = {0,0}; // variable for reading the pushbutton status

int previousState[]={0,0,0,0,0,0,0,0}; // array for holding the previous state of the input button

void setup()
{
//initialize the output pins that will control lights

pinMode(6,OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9,OUTPUT);

pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13,OUTPUT);
pinMode(14,OUTPUT);

// initialize the pushbutton pin as an input:
//set all light switches to the same block ie pins 30 - 35
byte i;
//this loop sets all the 30-35pins as inputs
for (i=30;i< 37;i++) {
pinMode(i, INPUT);
digitalWrite(i,HIGH); // this makes it connect to the internal resistor
}
}

void loop()
{
int arrayPosition;
for (int z = 0; z < 7; ++z)//zero based array needs to be as many as there are zones!!!
{
buttonState[z] = digitalRead(z+30);
for (arrayPosition = 0;zones[z][arrayPosition] ; arrayPosition++)
{
if ((buttonState[z] == HIGH) ) && (previousState[z] == LOW )) {
// turn LED on:
digitalWrite(zones[z][arrayPosition],HIGH);

}
else if ((buttonState[z] == LOW) && (previousState[z] == HIGH )) {
// turn LED off;
digitalWrite(zones[z][arrayPosition],LOW);

}

}
//each light assigned to the zone has been turned on or off, now set previousstate
//the statement is here the inner loop has finsihed turning lights on or off that belong to that zone
previousState[z] = buttonState[z];
}
}

最佳答案

您将两个元素分配给数组 buttonState,但您正在访问七个:

[…]
int buttonState[] = {0,0};
[…]
for (int z = 0; z < 7; ++z)
{
buttonState[z] = digitalRead(z+30);
[…]

您应该将 buttonState 数组中的元素数量增加到您实际需要的数量。

在一个地方定义数组的大小可能会更好:

#define NUM_ZONES (7)
[…]
const int * zones[NUM_ZONES]={zone2,zone3,zone4,zone5,zone6,zone7,zone8};

int buttonState[NUM_ZONES] = {0,0,0,0,0,0,0};

int previousState[NUM_ZONES]={0,0,0,0,0,0,0};

[…]
for (int z = 0; z < NUM_ZONES; ++z)
[…]

这还会显示您的 previousState 数组比需要的要大(编译器会提示该数组的初始化程序太多)。然后重要的是在任何地方重复使用该常量,而不是编写魔数(Magic Number) 7

关于c - Arduino 阵列问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34103553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com