【发布时间】:2015-12-05 18:28:48
【问题描述】:
您好,我正在做一个使用 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];
}
}
【问题讨论】:
-
为什么当我排除previousState时if条件起作用。它不会有两个元素但访问七个元素的相同问题吗??